What is the React.js way of handling visibility=hidden?

React does not support the visibility attribute for elements.

So if I want to show or hide an element on the page, but still have it take up space when hidden so the layout doesn’t shift, how do I do something like this?

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

You can use a CSS class for that and dynamically modify your className. For example:

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

Method 3

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

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

Method 4

Or you can just do it like this in your react 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>

Method 5

What is your use case? Do you want to…

  1. remove and add the component from the DOM?
  2. use CSS to hide or show the component? The component is always in the DOM
  3. re-render a new component. This causes the DOM to re-render.

Use component to state to manage the show hide effect.

class ExampleShowHide extends React.Component {
    constructor(props) {
       super(props);
           this.state = {
               show: false, 
           };
        this.toggleShowHide = this.toggleShowHide.bind(this);
     }

    toggleShowHide() {
        this.setState(oldState => ({show: !oldState.show}));
    }

    render() {
        return(<>
            <a onClick={() => this.toggleShowHide()}> Toggle </a>
        </>)
    }
}

The above will toggle the state prop ‘show’ from true and false.
Now you have three options. All three options are done in render()
  1. Let’s have the toggle completely remove and add a component from the DOM.

    { this.state.show && <MyComponent /> }
  1. Let’s keep the component in the DOM but hide and show using CSS.

    <div style={{
       visibility: this.state.showCreditCardFrom ? "visible" : "hidden",
    }}>
        <MyComponent />
   </div>
  1. Let’s cause a complete re-render

    render() {
        if(this.state.show) {
            return <MyComponent />
        } else {
            return <></>
        }
    }

Method 6

While the accepted answer works perfectly, I want to mention the classnames NPM package as an alternative way of implementing it in a more DRY-friendly way. With that package, you don’t need to copy the other, static classes between two strings:

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

Method 7

You could use string interpolation to add a css class:

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

Method 8

Solution with using style attribute and TypeScript:

import React, { CSSProperties } from 'react';

...
const style: CSSProperties = {
    visibility: this.state.showButton ? 'visible': 'hidden',
  };

const someJSXElement = (
    <i className="fa fa-trash" style={style} />
);

I suppose in vanilla JS you don’t need to typecast:
import React from 'react';

...
const style = {
    visibility: this.state.showButton ? 'visible': 'hidden',
  };

const someJSXElement = (
    <i className="fa fa-trash" style={style} />
);

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

Method 9

Or just use the ternary operator:

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x