Languages

React - how to stop page reloading onSubmit?

3 points
Asked by:
Dirask Community
5460

I'm trying to add some items to the list but when onSubmit event occurs my App is re-rendering without new item. Do you know how to fix this?

My code:

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines while working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

const initialList = [
  '🍏 Apple',
  '🍌 Banana',
  '🍒 Cherry',
  '🥝 Kiwi',
  '🍇 Grapes',
];

const App = () => {
  const [value, setValue] = React.useState('');
  const [list, setList] = React.useState(initialList);

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

  const handleSubmit = () => {
    if (value) {
      setList(list.concat(value));
    }
    setValue('');
  };

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

      <form onSubmit={handleSubmit}>
        <input type="text" value={value} onChange={handleChange} />
        <button type="submit">Add Item</button>
      </form>
    </div>
  );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );
1 answer
4 points
Answered by:
Dirask Community
5460

I found the solution:

The problem was I forgot to pass event as props to the handleSubmit method like I did with handleChange. Then I used event.preventDefault(); which prevented App re-rendering.

Runnable example:

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines while working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

const initialList = [
 '🍏 Apple',
 '🍌 Banana',
 '🍒 Cherry',
 '🥝 Kiwi',
 '🍇 Grapes',
];

const App = () => {
 const [value, setValue] = React.useState('');
 const [list, setList] = React.useState(initialList);

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

 const handleSubmit = (event) => {
   if (value) {
     setList(list.concat(value));
   }
   setValue('');

   event.preventDefault();
 };

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

     <form onSubmit={handleSubmit}>
       <input type="text" value={value} onChange={handleChange} />
       <button type="submit">Add Item</button>
     </form>
   </div>
 );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );
0 comments Add comment
Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join