How to open a component using onClick in React Js.

To open a component using `onClick` in React, you can create a state variable to track whether the component should be displayed or hidden. Here’s an example of how to do this:

  1. Create a state variable to track whether the component should be displayed or hidden:
import React, { useState } from 'react';
import ComponentToOpen from './ComponentToOpen';

function App() {
  const [isOpen, setIsOpen] = useState(false);

  function handleClick() {
    setIsOpen(!isOpen);
  }

  return (
    <div>
      <button onClick={handleClick}>Open Component</button>
      {isOpen && <ComponentToOpen />}
    </div>
  );
}

export default App;

  1. Create the `ComponentToOpen` the component that will be displayed when the button is clicked:
import React from 'react';

function ComponentToOpen() {
  return (
    <div>
      <h2>This is the component that opens!</h2>
      <p>You can put any content you want here.</p>
    </div>
  );
}

export default ComponentToOpen;

In this example, we’ve created a state variable called `isOpen` using the `useState` hook to track whether the component should be displayed or hidden. We’ve created a `handleClick` function that toggles the value of isOpen when the button is clicked. We’ve rendered a button that calls the `handleClick` function when clicked, and we’ve used a conditional statement to display the `ComponentToOpen` component when `isOpen` is true.

Now, when the button is clicked, the `ComponentToOpen` component will be displayed. When the button is clicked again, the `ComponentToOpen` component will be hidden.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top