Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

update of a buttons style on call of useState. how to convert variable of an object to string?

I want to update the style of button whenever is clicked.

I can’t use true/false to change the state because in query 2 objects with similar value.. so whenever one is clecked these both are getting changed style

Currently when button clicked happens nothing, except that useEffect outputs in console correct value.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

It seems that this problem in const onClick, it returns value in string:
Object { thisVal: "40", thisIndex: "0" }
Object { thisVal: "40", thisIndex: 0 }

Maybe you can suggest something?

          ...

  const [thisButtomSelected, setThisButtomSelected] = useState({
    thisVal: 0,
    thisIndex: 0,
  })
   const onClick = e => {  
    setThisButtomSelected({ thisVal: e.currentTarget.value, thisIndex: e.currentTarget.id });
  }

  useEffect(() => {
    console.log(thisButtomSelected)
  }, [thisButtomSelected])

       ...

  <li id="list" key={item.id}>
    <button
      value={item.value}
      id={index}
      className={isEqual(thisButtomSelected, { thisVal: item.value, thisIndex: index }) 
        ? 'button-selected' : 'button'
      }
      onClick={onClick}
    >
      {console.log(thisButtomSelected)}
      {console.log({ thisVal: item.value, thisIndex: index })}
      {item.displayValue}
    </button>
</li>
    ...

{item.value}, {index} and so on are taken from useQuery (apollo-client) and map was used

>Solution :

Here you go:

const onClick = e => {  
    setThisButtomSelected({ thisVal: parseInt(e.currentTarget.value), thisIndex: e.currentTarget.id });
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading