Skip to content
Advertisement

How to Pass Props into Styled Components?

I am trying to create an React App with such that background-color will be set based on a prop.

The App component maintains isDarkMode state which is a Boolean and is passed into the Header component and use it in styling the background-color of the Header Component via Styled components. Please see the codes below for more info

const App = function () {

  const [isDarkMode, setIsDarkMode] = React.useState(true)

  return (
    <main>
      <Header mode = {isDarkMode}/>
    </main>
  )
}

const Section = styled.section`
    background-color: ${props => props.mode === true? "yellow" : "blue"};
    padding: 0 80px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
`

export default function Header (props) {
    console.log(props)
    return (
        <Section >
            <span >Where in the world?</span>
            <FontAwesomeIcon icon={faMoon} />
            <span >DarkMode</span>
        </Section>
    )
}

The problem here is that the background-color for the Header component is blue even when the isDarkMode is set to true. My intention is to be able to set the background-color in the Header Component based on the value of the isDarkMode.

Please help

Advertisement

Answer

You are quite there. You just need to pass mode as a prop to the Section component:

<Section mode={props.mode}>

Docs: https://styled-components.com/docs/basics#adapting-based-on-props

Advertisement