Languages
[Edit]
EN

React - how to show or hide element

1 points
Created by:
Dirask Community
1700

In this article we would like to show you how to show or hide elements in React.

One button solution

In below example we present a simple solution with one button which hides and shows our element (<div>My element</div>).

We use React.useState hook to store the state of our element (if it's visible or not).
By default the value of visible object is set to false so the element is hidden.
To show it we need to change visible value to true by passing negated visible argument to the event handling onClick function

// ONLINE-RUNNER:browser;

//Note: Uncomment import lines during working with JSX Compiler.

// import React from 'react';

const App = () => {
    const [visible, setVisible] = React.useState(false);
    return (
      <div>
        <button onClick={() => setVisible(!visible)}>
          {visible ? 'Hide' : 'Show'}
        </button>
        {visible && <div>My element</div>}
      </div>
    );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );

Two buttons solution

In below example we present a solution with two separate button components to show and hide our element (<div>My element</div>).

We use React.useState hook to store the state of our element (if it's visible or not).
By default the value of visible object is set to false so the element is hidden.
To show it we create a button which calls setVisible funtion on click event with true argument, so our element can be visible now.
To hide the element we call setVisible function which sets visible value to false.

// ONLINE-RUNNER:browser;

//Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';

const App = () => {
    const [visible, setVisible] = React.useState(false);
    return (
      <div>
        <button onClick={() => setVisible(true)}>Show</button>
        <button onClick={() => setVisible(false)}>Hide</button>
        {visible && <div>My element</div>}
      </div>
    );
  };

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );

ReactJS

Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - friendly IT community for everyone.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join