简体   繁体   中英

Adding CSS to react/JSX to hide a component

I am hiding and showing a component based on the state of a checkbox, and I am using a ternary operator to decide whether the component is shown or hidden. However, this component is handling data so it would be better to just hide the component with CSS, because every time the component is re-shown, it creates a new request. Below is the ternary operator:

const displayWidget = this.state.checked ? <Widget /> : null;

I have looked other examples trying to accomplish the same, some suggesting something like:

const divStyle = {
   visibility: 'hidden',
}

const displayWidget = this.state.checked ? <Widget /> : <Widget style= {divStyle} />`

Is the second example the right way to go about it and I'm just doing something wrong, or is there another way to go about solving this problem?

The simple answer is you can do either, it is simply based on your requirements.

Returning null

const displayWidget = this.state.checked ? <Widget /> : null;

Doing it this way means that when this.state.checked is true then your Widget component is mounted and componentWillMount / componentDidMount will be called.

However, when this.state.checked is false the Widget component will unmount and if you stick a console.log in the componentWillUnmount function you will see this.

If this.state.checked is true (again) then your Widget component is mounted (again) and componentWillMount / componentDidMount will be called (again).

Hiding via css

I would change your code to this:

const divStyle = {
   visibility: 'hidden',
}

const displayWidget = <Widget style= {...this.state.checked ? {} : divStyle} />

This way means that on initial render and this.state.checked is true then it will mount in the same way as the null approach.

However, when this.state.checked is false , unmount is NOT called as the component is still mounted but is now simply being hidden via css .

A alternative approach to hiding a component but keeping it mounted

<Widget visible={this.state.checked} />

And in the render() method of your Widget component you could do something like:

render() {
  if (!this.props.visible) {
    return null;
  }
  return <span>widget content</span>;
}

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