Home > Enterprise >  How to style a component based on state in Styled Components?
How to style a component based on state in Styled Components?

Time:01-08

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.

CodePudding user response:

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'

CodePudding user response:

Add 'props' in styled-component like this;

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

CodePudding user response:

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);
      }}
    />
  );
}
  •  Tags:  
  • Related