What is the React.js visibility = hidden method?

Reacts the visibility attribute support for elements.

So, if I want to show or hide an element on the page, but still you have a place to hide, so that the layout does not move, how can I do something like this?

<i className="fa fa-trash" visibility={this.state.showButton ? "visible": "hidden"} /> 
+17
reactjs
source share
6 answers

You can use the CSS class for this and dynamically change your class name. For example:

<i className={this.state.showButton ? "fa fa-trash" : "fa fa-trash hidden"} />

+13
source share

You can use CSS for this.

 <i className="fa fa-trash" style={{visibility: this.state.showButton ? 'visible' : 'hidden' }} /> 

Learn more about inline styles in React.

+16
source share

This is a css attribute, so you can use the inline styles:

 ... var visibilityState = this.state.showButton ? "visible" : "hidden"; return ( <i className="fa fa-trash" style={{visibility: visibilityState}}/> ); ... 
+3
source share

Although the accepted answer works fine, I want to mention the classnames NPM package as an alternative way to implement it in a more DRY-friendly way. With this package you do not need to copy other static classes between two lines:

 <i className={classNames("fa", "fa-trash", {"hidden": !this.state.showButton})} /> 
+1
source share

You can use string interpolation to add a CSS class:

 <i className={'fa fa-trash ${this.state.showButton ? "" : "hidden"}'} /> 
+1
source share

Or you can just do it in your reaction component

 { this.state.showButton && <i className="fa fa-trash" /> } 

 // Get a hook function const {useState} = React; const Example = ({title}) => { const [visible, setVisible] = useState(false); return ( <div> <p>{title}</p> <button onClick={() => setVisible(!visible)}> visibility : {!visible ? "hidden" : "showing"} </button> {visible && <p>Its toggling visibility</p>} </div> ); }; // Render it ReactDOM.render( <Example title="Example using Hooks:" />, document.getElementById("react") ); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="react"></div> 

0
source share

All Articles