How to remove a component in React.js.

Toggling the display state of a component is one of the defining purposes of modern frontend frameworks. UI elements are added and removed consistently throughout most workflows. With each UI segment representing a component, it makes sense to be able to remove it with ease.

So, how do you remove a component in React.js? The best way to remove a component in React.js is to render it conditionally using ternary operators and state.

Let’s say we have a functional component called HeaderText:

function HeaderText (props) {
  return <h1>{props.title}</h1>;
}
  • We want to toggle this text component to display based on a button click.
  • Let’s create an App component that uses showButton state to toggle the display of HeaderText
// import header component here
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showButton: false,
    };
  }

 toggleButton = () => {
    this.setState({ showButton: !this.state.showButton });
  };

  render() {
    const { showButton } = this.state;
    return (
      <div>
        <button onClick={() => this.toggleButton()}>Click me</button>
        {showButton ? <HeaderText title="Hello React"/> : null}
      </div>
    );
  }
}

Let go over what’s happening here:

  • When clicked, our showButton state will change
    • If already false –> true, if already true –> false
  • When it’s false, our ternary operator (?) will not render <HeaderText /> and will instead render null.
    • This is essentially how you removed a component in React.js

And there you have it. Remember, you can always add or remove any component in React.js using state and conditional rendering.

Proudly published with Gatsby