I am building a simple react app where a user enters a number and it is displayed on the screen.
class Main extends React.Component {
state = {
list: [1,2,3,4,5]
}
newElementHandler = (e) => {
let newlist = this.state.list
newlist.push(e.target.value)
this.setState({
list: newlist
})
}
submitHandler = (e) => {
e.preventDefault()
}
render() {
let showlist = this.state.list
return (
<div>
<div>
{showlist.map(ele=>(
<div>{ele}</div>
))}
</div>
<form onSubmit={this.submitHandler}>
<input onChange={this.newElementHandler} />
<button type="submit" >Submit</button>
</form>
</div>
)
}
}
ReactDOM.render(<Main />, document.querySelector('.react'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div class='react'></div>
However, I only want the number to be displayed when clicked "Submit". Right now, it displays the number as soon as i start typing. Can someone please help modify this code so that it only updates the state on form submission and hence displays the number. Thanks