Reputation: 5488
How do I update the App
function so the data contained in state is pushed to an array each time the button is pushed?
I've tried using something like array.push(this.state)
but would appreciate some guidance.
I have found examples using class components but not React hooks. Does it require something like useEffect
?
import React, { Component, useState, setState } from 'react';
import { render } from 'react-dom';
const App = () => {
const [value, setValue] = useState('');
const handleChange = event => setValue(event.target.value);
return (
<div>
<label>
Input:
<input type="text" value={value} onChange={handleChange} />
<input type="button" value="Click Me" onClick={?????}/>
</label>
</div>
);
};
render(<App />, document.getElementById('root'));
Upvotes: 0
Views: 820
Reputation: 3274
You need to create a ref for your array so that its content is preserved after an update:
const arrayRef = useRef([]);
Then you create an onClick function:
const onClick = () => {
arrayRef.current.push(value);
}
And call that function from your button:
<input type="button" value="Click Me" onClick={onClick}/>
Upvotes: 1