gospecomid12
gospecomid12

Reputation: 1012

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;

Upvotes: 1

Views: 7921

Answers (3)

Abu Sayed
Abu Sayed

Reputation: 187

export default function App() {
  const [time, setTime] = React.useState(0);
  const [start, setStart] = React.useState(false);
  let [laps, setLaps] = React.useState([]);

  React.useEffect(() => {
    let interval = null;

    if (start) {
      interval = setInterval(() => {
        setTime((t) => t + 10);
      }, 10);
    } else {
      clearInterval(interval);
    }

    return () => clearInterval(interval);
  }, [start]);

  let m = Math.floor((time / 60000) % 60);
  let s = Math.floor((time / 1000) % 60);
  let ms = Math.floor((time / 10) % 100);

  m < 10 ? (m = '0' + m) : m;
  s < 10 ? (s = '0' + s) : s;
  ms < 10 ? (ms = '0' + ms) : ms;

  let stop_watch = `${m}:${s}:${ms}`;

  const lapHandel = () => {
    setLaps([...laps, stop_watch]);
  };

  console.log(laps);

  
}

Upvotes: 0

Tasos
Tasos

Reputation: 2045

you need to update the foodList state hook with the new array:

const handleClick = event => {   
  setFoodList((_foodlist) => [..._foodlist, { new element values }]);
}

That's pretty much it, if you update the state, the component will re-render and show the updated foodList.

EDIT #1: I used the callback way inside the setFoodList so that there is no race condition if the user clicks the button very fast. It's an edge case but a nice to have.

Upvotes: 3

Giorgi Moniava
Giorgi Moniava

Reputation: 28685

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

Upvotes: 5

Related Questions