Sasa Mirkov
Sasa Mirkov

Reputation: 15

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

Upvotes: 1

Views: 49

Answers (2)

Marcos Raimundo
Marcos Raimundo

Reputation: 46

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)
        }
      }

Upvotes: 1

Marcos Raimundo
Marcos Raimundo

Reputation: 46

I couldn't quite understand your end goal, but from what I understand you want to update the value in a component. For that you can use the useState of React Hooks and the click event of the button. example: https://codesandbox.io/s/6vryxv96pz

import React, { useState } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const App = () => {
  const [value, setValue] = useState("");
  const [list, setList] = useState(["a", "b", "c"]);

  const onChangeValue = (event) => {
    setValue(event.target.value);
  };

  const onAddItem = () => {
    setList((prevState) => {
      const list = [...prevState, value];
      return list;
    });
    setValue("");
  };

  return (
    <div>
      <ul>
        {list.map((item, i) => (
          <li key={i}>
            <div>{item}</div>
          </li>
        ))}
      </ul>

      <input type="text" value={value} onChange={onChangeValue} />
      <button type="button" onClick={onAddItem} disabled={!value}>
        Add
      </button>
    </div>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Upvotes: 1

Related Questions