Search code examples
javascriptreactjsantd

Updating react component


I have this piece of code:

let columnChooser = [productName]

      function replacer (key: any) {

        if (key == 1) {
            message.info(`Click on item ${key}`);
            columnChooser.push(productPrice)
        }
      }

what I want basically is to add productPrice into the existing array. With this method in my react return Ido not get a new column productPrice, I constantly have only productName. the function is from the drop-down menu and it grabs key values so an appropriate column can be added to the array.

Can anyone provide me with some insight into why this is not working

after function is run via button press I expected that new value be added into array and shown in front end


Solution

  • in this case you need to use useState. Then your code would look like this:

    // let columnChooser = [productName]
       const [columnChooser, setColumnChooser] = useState ([productName]);
    
          function replacer (key: any) {
    
            if (key == 1) {
                message.info(`Click on item ${key}`);
                setColumnChooser(prevState => [...prevState, productPrice]);
               // columnChooser.push(productPrice)
            }
          }