Home > Enterprise >  Stop page reloads after onClick() event - react
Stop page reloads after onClick() event - react

Time:05-23

Hi I am having trouble with an onClick() event in my react code. It is supposed to store an ingredient as an object into an array but currently it reloads the page. I belive i am supposed to use e.stopPropagation() or e.preventDefault but I think I am putting them in the wrong spot.

export default function Recipe() {
  const [name, setName] = useState('')
  const [ingredientList, setIngredientList] = useState([
    {
      ingredient_name: '',
      quantity: '',
      measure: '',
    },
  ])
  
  const handleChange = (e, i) => {
    const { name, value } = e.target

    setIngredientList((prevState) => {
      // e.stopPropagation()
      // e.preventDefault()
      const newIngredientList = [...prevState]
      newIngredientList[i][name] = value

      return [...newIngredientList]
    })
  }
[...]
     {ingredientList.map((list, i) => (
            <div key={i} className="ingredient-triad">
              <input
                className="ingredient"
                name="ingredient_name"
                type="text"
                value={list.ingredient_name}
                onChange={(e) => handleChange(e, i)}
              ></input>
              <input
                className="quantity"
                name="quantity"
                type="text"
                value={list.quantity}
                onChange={(e) => handleChange(e, i)}
              ></input>
              <select
                className="dropdown"
                name="measure"
                id="measure"
                value={list.measure}
                onChange={(e) => handleChange(e, i)}
              >
                <option value="" disabled>
                  --none--
                </option>
                <option value="cup">cup</option>
              </select>
              <button
                onClick={() => setIngredientList((prev) => [...prev, init])}
              >
                Add
              </button>
            </div>
          ))}
        </form>
      </div>
    </div>
  )
}
[...]

CodePudding user response:

Add it here:

<button onClick={() => setIngredientList((prev) => [...prev, init])}>
Add
</button>

to:

<button onClick={(e) => {
e.preventDefault()
setIngredientList((prev) => [...prev, init])
}}>
Add
</button>

CodePudding user response:

Here is the script that I saved for stopping propagation. I put it as the first line in my method.

if (!event) event = window.event;
event.cancelBubble = true;
if (event.stopPropagation) event.stopPropagation();
  • Related