EN
React - how to stop page reloading onSubmit?
1 answers
3 points
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:
xxxxxxxxxx
1
// Note: Uncomment import lines while working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const initialList = [
6
'🍏 Apple',
7
'🍌 Banana',
8
'🍒 Cherry',
9
'🥝 Kiwi',
10
'🍇 Grapes',
11
];
12
13
const App = () => {
14
const [value, setValue] = React.useState('');
15
const [list, setList] = React.useState(initialList);
16
17
const handleChange = (event) => {
18
setValue(event.target.value);
19
};
20
21
const handleSubmit = () => {
22
if (value) {
23
setList(list.concat(value));
24
}
25
setValue('');
26
};
27
28
return (
29
<div>
30
<ul>
31
{list.map((item) => (
32
<li key={item}>{item}</li>
33
))}
34
</ul>
35
36
<form onSubmit={handleSubmit}>
37
<input type="text" value={value} onChange={handleChange} />
38
<button type="submit">Add Item</button>
39
</form>
40
</div>
41
);
42
};
43
44
const root = document.querySelector('#root');
45
ReactDOM.render(<App />, root );
1 answer
4 points
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:
xxxxxxxxxx
1
// Note: Uncomment import lines while working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const initialList = [
6
'🍏 Apple',
7
'🍌 Banana',
8
'🍒 Cherry',
9
'🥝 Kiwi',
10
'🍇 Grapes',
11
];
12
13
const App = () => {
14
const [value, setValue] = React.useState('');
15
const [list, setList] = React.useState(initialList);
16
17
const handleChange = (event) => {
18
setValue(event.target.value);
19
};
20
21
const handleSubmit = (event) => {
22
if (value) {
23
setList(list.concat(value));
24
}
25
setValue('');
26
27
event.preventDefault();
28
};
29
30
return (
31
<div>
32
<ul>
33
{list.map((item) => (
34
<li key={item}>{item}</li>
35
))}
36
</ul>
37
38
<form onSubmit={handleSubmit}>
39
<input type="text" value={value} onChange={handleChange} />
40
<button type="submit">Add Item</button>
41
</form>
42
</div>
43
);
44
};
45
46
const root = document.querySelector('#root');
47
ReactDOM.render(<App />, root );
0 commentsShow commentsAdd comment