4

I am trying to change the input background based on the useState hook in Styled Components in React.

Here is my code:

 const [searchActive, setSearchActive] = useState(true);
 <div className="search" searchActive={searchActive}>
     <input id="input"/> 
 </div>

Here is my Styled Component code:

.search {
    background: ${(searchActive) => (searchActive ? "red" : "yellow")};
   }

any advise would be very appreciated.

DᴀʀᴛʜVᴀᴅᴇʀ
  • 7,681
  • 17
  • 73
  • 127
Myrat
  • 347
  • 2
  • 4
  • 16

3 Answers3

1

Creating a component and passing in props will work:

import React from 'react'
import styled from 'styled-components'

const Search = styled.div`
  background: ${props => (props.searchActive ? 'red' : `yellow`)};
`

const Parent = () => {
  return (
      <Search searchActive={searchActive}>
        <input id="input" /> 
      </Search>
  )
}

export default Parent

Only different is whatever you have style wise for search can be added to the Search component but you do not show any further code so I do not know how you're bringing it in.

You can also externalize the components with something like:

import styled from 'styled-components'

export const Search = styled.div`
  background: ${props => (props.searchActive ? 'red' : `yellow`)};
`

then bring it in:

import {Search} from './search.js'
DᴀʀᴛʜVᴀᴅᴇʀ
  • 7,681
  • 17
  • 73
  • 127
0

Add 'props' in styled-component like this;

.search {
  background: ${props => props.searchActive? "red" : "yellow"};
}
0

You can declare and directly use Styled Components in jsx . They are not required to be used as a className. Maybe this approach is useful for you.

import React, { useState } from "react";
import styled from "styled-components";

export default function App() {
  const [searchActive, setSearchActive] = useState(true);
  const [value, setValue] = useState("");
  const Search = styled.input`
     background: ${(props) => (props.searchActive ? "red" : "yellow")};
  `;
  return (
    <Search
      searchActive={searchActive}
      value={value}
      onChange={(e) => {
        setValue(e.target.value);
        setSearchActive(false);
      }}
    />
  );
}
Sonam Gupta
  • 363
  • 2
  • 11
  • "It is important to define your styled components outside of the render method, otherwise it will be recreated on every single render pass." - https://styled-components.com/docs/basics#define-styled-components-outside-of-the-render-method – Mendes Aug 11 '22 at 13:43