0

I have buttons iteratively rendered from their parent. I want to change each button's text individually on click. Code as follows:

function App() {
  
  const [btnText, setBtnText] = useState('Add to cart');
  
  const handleClick = () => {
    setBtnText('Remove from cart');
  };
  
  const btnTexts = [
    {
      id: 1,
      btnText: btnText
    },
    {
      id: 2,
      btnText: btnText
    }
  ]

  const renderBtns = () => {
    btnTexts.map((b) => {
      return(
        <button onClick={handleClick}>{b.btnText}</button>
      )
    })
  }
  return (
    <div className="App">
      {renderCards(cardDetails)}
    </div>
  );
}

Initially both buttons show text: "Add to cart". When clicking on a button, both buttons' text change to "Remove from cart". I understand this is due to both buttons' have the same state, but how can I make only the clicked button show "Remove from cart"?

one-hand-octopus
  • 2,229
  • 1
  • 17
  • 51
  • if you only have 2 buttons, the simplest and probably best solution is just to use 2 separate state variables. If there could be a lot more you might do something more sophisticated like an array of button texts as your state. Using `useReducer` rather than `useState` might make the array solution a big cleaner as well, as you can dispatch an action that says clearly "change the text at index i". – Robin Zigmond Jul 27 '22 at 22:31
  • @RobinZigmond I have many buttons so using 2 states is not possible. Also I don't want to repeat `handleClick` function – one-hand-octopus Jul 27 '22 at 22:34
  • 1
    so go with an array as your state, as I suggested – Robin Zigmond Jul 27 '22 at 22:35
  • 2
    The buttons should probably be their own components, controlling their own state. Then the state changes are locally scoped for each one and you still only have to write one set of handlers. But to be honest the question seems overly contrived. The text for the button should be derived from something useful like the state of the cart. If cart has item, render remove text, it doesn't then render add text. – lawrence-witt Jul 27 '22 at 22:37

0 Answers0