2

Say I have the following array:

    import {useState} from 'react';
    
    const [products, setProducts] = useState([
      {name: "Television", price: 1000},
      {name: "Cellphone", price: 800},
      {name: "Pen", price: 1}
    ])

and the following inputs and a button on another component:

<input placeholder="Name" value={} onChange={} />
<input placeholder="Price" value={} onChange={} />
<button onClick={insert function here}>Save</button>

How does one grab the new value from both inputs and add them as a new array to the original products array so that the result would be:

[
          {name: "Television", price: 1000},
          {name: "Cellphone", price: 800},
          {name: "Pen", price: 1},
          {name: "Chocolate", price: 5}
        ]

and not:

[
          {name: "Television", price: 1000},
          {name: "Cellphone", price: 800},
          {name: "Pen", price: 1},
          {name: "Chocolate"},
          {price: 5},
        ]

Thank you!

2
  • Hey Lucas, and welcome. It would be very helpful to post the function you're currently running to add the values to your array so we can help debug ;) Commented May 25, 2021 at 14:59
  • when you want to push the value to the product List , onClick of save ? Commented May 25, 2021 at 15:07

2 Answers 2

1

You can do this a couple of ways, I'll highlight one here as an example and mention others below.

For input fields, you want to store the value in state, for a functional component, that would like this:

export const MyComponent = () => {
  const [products, setProducts] = useState([
    {name: "Television", price: 1000},
    {name: "Cellphone", price: 800},
    {name: "Pen", price: 1}
  ]);
  const [name, setName] = useState('');
  const [price, setPrice] = useState(0);

  const addProduct = () => {
    setProducts([...products, {name, price}]);
  };

  return (
    <input placeholder="Name" value={name} onChange={(e) => setName(e.target.value)} />
    <input placeholder="Price" value={price} onChange={(e) => setPrice(e.target.value)} />
    <button onClick={addProduct}>Save</button>
  ); 
};

In this example, we're using state to control the input values documentation. You can also make this more dynamic with multiple inputs that are child components and you can add many at once. It is very extensible.

An alternative approach would be to store a ref to the inputs and grab the values when you click. In general you'd want react to control the inputs, but there are exceptions. You can read more about ref here: documentation

Additional Note on syntax: In the above example, we're using array destructuring to add a value to the array. This creates a new array and helps to keep in mind that the products array is immutable and changes to it won't be reflected in the component.

Sign up to request clarification or add additional context in comments.

2 Comments

The issue with this approach is, when the user adds a name of the product for example laptop and hits save . The products Array will have an entry with { name: 'laptop', price: 0 } . So a validation must be in place so that the user should not be able to save unless both the name and price are filled .
@Shyam Yes, that's a great point. However, the question doesn't really address the needs around this functionality. As asked, this can handle the functionality requested. The OP is free to add additional validation and checks as needed. I intentionally left this answer simple in order to not make assumptions. For example, the button is called Save, so you could assume they are submitting a form and that there is additional functionality involved with that. For the purpose of the question, I did not make further assumptions about their app.
0

first of all you need two states for your inputs :

const [name,setName] = useState("");
const [price,setPrice] = useState(0);

now you have to connect your inputs to your states:

<input placeholder="what ever" value={name} onChange={(e)=>{setName(e.target.vaklue)}} />

<input placeholder="what ever" value={price} onChange={e=>{setPrice(e.target.value)}} />

and in button you have a submit function in onClick like this :

function handleSubmit(){
    setProduct([...products,{name,product}]);
}

.

<button onClick={handleSubmit}>Save</button>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.