Search code examples
javascriptarraysreactjshigher-order-functions

How to add elements to array on click in react?


Im pretty new to react (i have only worked with classes abit) and I want to add my input values to foodList and write them out on the screen but my brain is locked and i cant figure out how...

Any tips would help, thanks!

import React, {useState, useEffect} from 'react';


const Form = () => {

    const [recipe, setRecipe] = useState("");
    const [ingrediens, setIngrediens] = useState("");
    const [foodList, setFoodList] = useState([])

    const handleChange = event => {
        setIngrediens({[event.target.name]: event.target.value})
        setRecipe({[event.target.name]: event.target.value})
    }

    const handleClick = event => {   // Here is where i get problem

    }   

    return (
        <main>
            <button onClick={handleClick}>add</button>
            <div className="form">
            <input type="text" placeholder="Enter your recipe" name="recipe" onChange={handleChange} ></input>
            <input type="text" placeholder="Enter your ingrediens" name="ingrediens" onChange={handleChange} ></input>
            </div>

            <div className="results">
               <ul>
                   {foodList.map(i => (
                       <li key={i}> {recipe} <p> {ingrediens} </p> </li>
                   ))}
               </ul>
            </div>
        </main>
    )
}

export default Form;

Solution

  • I suppose you want something like this? I also refactored other parts of the code, like handleChange, which seemed bit weird.

    const Form = () => {
      const [recipe, setRecipe] = useState("");
      const [ingrediens, setIngrediens] = useState("");
      const [foodList, setFoodList] = useState([]);
    
      const handleChangeRecipe = event => {
        setRecipe(event.target.value);
      };
      const handleChangeIngredients = event => {
        setIngrediens(event.target.value);
      };
      const handleClick = event => {
        setFoodList([...foodList, { recipe: recipe, ingrediens: ingrediens }]);
      };
    
      console.log(foodList);
      return (
        <main>
          <button onClick={handleClick}>add</button>
          <div className="form">
            <input
              type="text"
              placeholder="Enter your recipe"
              name="recipe"
              onChange={handleChangeRecipe}
            />
            <input
              type="text"
              placeholder="Enter your ingrediens"
              name="ingrediens"
              onChange={handleChangeIngredients}
            />
          </div>
    
          <div className="results">
            <ul>
              {foodList.map((x, i) => (
                <li key={i}>
                  {" "}
                  {x.recipe} <p> {x.ingrediens} </p>{" "}
                </li>
              ))}
            </ul>
          </div>
        </main>
      );
    };