I tried to make a small program that has an input field where you can insert text. Then when you click save, it saves the text and shows you below. My question is that, initially the text was not showing up after I clicked 'save', but only when I made another change to the input field after clicking 'save'.
After adding this.setState({inputText: ' '}) in saveValue, it started to work but I'm not so sure why.
import React, {Component} from 'react'
import './App.css';
import picture from './picture.jpg'
class App extends Component {
state = {
inputText: '',
savedValues: [],
}
textStorage = (event) => {
this.setState({
inputText: event.target.value
})
}
saveValue = (inputText) => {
this.state.savedValues.push(this.state.inputText)
this.setState({inputText: ' '})
}
render() {
return (
<div className = "App">
<h1>Hello World</h1>
<input
type = "text"
value = {this.state.inputText}
onChange = {(event) => this.textStorage(event)}
/>
<p>Here's your text: {this.state.inputText}</p>
<button onClick = {this.saveValue}>Save</button>
<p>{this.state.savedValues.join('')}</p>
<div>
<img className = "Picture" src={picture} alt="Picture"/>
</div>
</div>
)
}
}
export default App;