Skip to content
Advertisement

Saving the state of the button onClick

I have:

<blink>

  const [thisButtomSelected, setThisButtomSelected] = useState(false);
  var thisButton = [];

  const onAttributeClick = (e) => {
    thisButton[e.currentTarget.value] = { thisID: e.currentTarget.id, thisName: e.currentTarget.name }
    setThisButtomSelected(thisButton[e.currentTarget.value]);
  }
  return(
    <div>
      {data.item.attributes.map((attribute, index) => (
        <div key={index} >
          <p id={attribute.id}>{attribute.name}:</p>

          <ul className="choose-attribute-container-ul">
            {attribute.items.map((item) => (

              <li key={item.id}>
                <button
                  value={item.value}
                  id={item.id}
                  name={attribute.name}
                  className={_.isEqual(thisButtomSelected, { thisID: item.id, thisName: attribute.name }) ? 'attribute-button-selected' : 'attribute-button'}
                  onClick={onAttributeClick}
                >
                  {item.displayValue}
                </button>
              </li>
            ))}
          </ul>
        </div>
      ))}
    </div>
  )

</blink>

This pattern works fine, but whenever on the page more then 1 attribute and user select more then one, previously selected button gets unclicked.
My question is: How can I save the state of 1st selected button after clicking on 2nd one?

  1. for each attribute only one button can be active
  2. buttons name should be used

Advertisement

Answer

You should save the buttons in an array to retain them all, something like that:

  const [thisButtomSelected, setThisButtomSelected] = useState([]);

  var thisButton = [];
  
  const onAttributeClick = (e) => {
      thisButton[e.currentTarget.value] = { thisID: e.currentTarget.id, thisName: e.currentTarget.name }
  
      setThisButtomSelected([...thisButtomSelected, thisButton[e.currentTarget.value]]);
  
  }
  return(
              <div>
                  {data.product.attributes.map((attribute, index) => (
                      <div key={index} >
                          <p id={attribute.id}>{attribute.name}:</p>
  
                          <ul className="choose-attribute-container-ul">
                              {attribute.items.map((item) => (
  
                                  <li key={item.id}>
                                      <button
                                          value={item.value}
                                          id={item.id}
                                          name={attribute.name}
                                          className={thisButtomSelected.find(el => el.thisID === item.id && el.thisName === attribute.name) ? 'attribute-button-selected' : 'attribute-button'}
                                          onClick={onAttributeClick}
                                      >
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement