1
votes

I'm able to change a styled components styles based on state but only at page load, if I toggle the state after page load, the state changes successfully but the styles remain the same. The styled component whose styles I'm trying to change is "S.Search" which is inside of a "Search" component whose parent is "Navbar". I'm passing "Search" an "isVisible" state as a prop that is toggled by the onClick event handler in the parent component "Navbar".

The parent component:


    import React, { useContext, useState } from "react"
    import Search from "../components/Search"
    import * as S from "../styled/Navbar"

    const Navbar = () => {

      const [isVisible, setVisibility] = useState(false)
      return (
        <S.Navbar>
          /* S.SearchButton toggles the isVisible state onclick */
              
              <S.SearchButton onClick={() => setVisibility(!isVisible)}>
                <S.SearchButtonText>Search</S.SearchButtonText>
              </S.SearchButton>
            
            /* Passing isVisible state into the Search component as props */
            
            <Search isVisible={isVisible} setVisibility={setVisibility} />
        </S.Navbar>
      )
    }

    export default Navbar

The search component:


    import React, { useState } from "react"
    import Icon from "../components/Icon"
    import * as S from "../styled/Search"

    const Search = props => {
      return (
        <S.Search>
          <S.InputWrapper>
            <S.SearchButtonIcon>
              <Icon icon={"search"} />
            </S.SearchButtonIcon>
            <S.Input
              type="text"
              placeholder="Search for a character"
              autocomplete="off"
            />
            <S.ChampList></S.ChampList>
          </S.InputWrapper>
        </S.Search>
      )
    }

    export default Search


I'm sure my state is being toggled correctly, but I have no idea why the style isn't being updated when toggling the state after page load. This is the styled component that has access to the isVisible state via props passed to the search component:


    import styled from "styled-components"

    export const Search = styled.div`
      height: ${p => (!p.isVisible ? `0` : `2.5rem`)};
      visibility: ${p => (!p.isVisible ? `hidden` : `visible`)};
      opacity: ${p => (!p.isVisible ? `0` : `100`)};
      display: flex;
      justify-content: center;
      transition: ${p => p.theme.easings.easeOut};

    `

How can I change the style after page load when I toggle the state? Thank you for your time!

1

1 Answers

2
votes

Your style isnt being applied because you are not passing isVisible prop to Search style-component.

You just need to do this in your Search Component:

const Search = props => {
      return (
        // Here“s the trick
        <S.Search isVisible={props.isVisible}>
         .....
         .....
         .....