简体   繁体   中英

Changing styles depends on state

I am trying to hide a component when the user had signed in already

const Container = styled.div`
  display: ${(props) => props.loggedIn ? 'none' : 'block'};
`

this.state {
  loggedIn: false
}

getUrl = () => {

  //conditions to determine if user already loggedIn {
    this.setState(prevState => ({
      loggedIn: !prevState.loggedIn,
   }));

}

componentDidMount() {
  this.getUrl()
}

render() {
return (
  <SomeComponent>
   <Row>
      <Col>
        <Navbar> Navbar </Navbar>
      </Col>
      <Col>
        <Container>
          <SomeStyles>
            //somestyles
          </SomeStyles>
          <Menu>
            //MenuList
          </Menu>
        </Container>
      </Col>
    <Row>
  </SomeComponent>
);
}
}

The setState is working already. But the problem is when I'm trying to pass it in Styled Components, It only get the default value of the "loggedIn" state which is false. So it always end up getting the 'block' value for the display.

You need to pass the loggedIn property to Container :

// Styled Container
const Container = styled.div`
  display: ${(props) => props.loggedIn ? 'none' : 'block'};
`

// Components tree
<SomeComponent>
  <Row>
    <Col>
      <Navbar> Navbar </Navbar>
    </Col>
    <Col>
      <Container loggedIn={this.state.loggedIn}>
        <SomeStyles/>
        <Menu/>
      </Container>
    </Col>
  </Row>
</SomeComponent>

I think you should use state instead of props in your style, as props is readonly and your changes is only effect the state

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM