I have a certain number of buttons, clicking on one should show content only for it in React Component

To show content only for the button that was clicked in a React component, you can use state to keep track of the selected button. Here's a simple example:


javascript

Copy code

import React, { useState } from 'react';


function ButtonContent() {

  const [selectedButton, setSelectedButton] = useState(null);


  const handleClick = (button) => {

    setSelectedButton(button);

  };


  return (

    <div>

      <button onClick={() => handleClick(1)}>Button 1</button>

      <button onClick={() => handleClick(2)}>Button 2</button>

      <button onClick={() => handleClick(3)}>Button 3</button>

      {selectedButton === 1 && <div>Content for button 1</div>}

      {selectedButton === 2 && <div>Content for button 2</div>}

      {selectedButton === 3 && <div>Content for button 3</div>}

    </div>

  );

}


export default ButtonContent;

In this example, the selectedButton state variable keeps track of the selected button. The handleClick function updates the selectedButton state when a button is clicked. The content for each button is shown using a conditional render, which checks if the selectedButton state matches the button ID.


This is just a simple example to show the basic idea. You can modify the code to fit your specific requirements.


If you want to show the content for a button when it is first loaded, you can set the initial value of the selectedButton state to the button ID that you want to show the content for:


scss

Copy code

const [selectedButton, setSelectedButton] = useState(1);

In this example, the content for button 1 will be shown when the component is first rendered.


You can also use this technique to show different content for each button based on its ID. Just modify the content inside the conditional render to match your specific requirements.


I hope this helps! Let me know if you need anything else.

Post a Comment

Previous Post Next Post