1

I'm trying to get the value of input onChange and I got really confused. (the function should take user input and display in html)

export class App extends React.Component {
constructor (props) {
super(props)
this.state = {
  date: new Date(),
  inputText: ''
}
this.handleChange = this.handleChange.bind(this)
this.submitChange = this.submitChange.bind(this)
}
handleChange (event) {
 this.setState({
  [event.target.name]: event.target.value
})
}
submitChange (event) {
 event.preventDefault()
 this.setState({
  inputText: true
})
}
render () {
return (
<form onSubmit={this.submitChange}>
      <input type='text' className='text_appoint' name='inputText' value={this.state.inputText} onChange={this.handleChange} placeholder='Typeing ...' />
</form>
<button className='submit' onClick={this.submitChange} value='Submit'>
<div> </div>
0

1 Answer 1

3

Here's one way of doing that. You can track if the button has been clicked in state, and when it is show the output:

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      submitted: false,
      date: new Date(),
      inputText: ''
    }
    this.handleChange = this.handleChange.bind(this)
    this.submitChange = this.submitChange.bind(this)
  }
  handleChange(event) {
    this.setState({
      [event.target.name]: event.target.value
    })
  }
  submitChange(event) {
    event.preventDefault()
    this.setState({
      submitted: true,
      inputText: this.state.inputText,
    })
  }
  render() {
    return ( 
    <div >
      <form onSubmit = { this.submitChange } >
      <input type = 'text'
      className = 'text_appoint'
      name = 'inputText'
      value = {
        this.state.inputText
      }
      onChange = {
        this.handleChange
      }
      placeholder = 'Typeing ...' / >
      </form>
      <
      button className = 'submit'
      onClick = {
        this.submitChange
      }
      value = 'Submit' > Submit < /button> <
      p id = "submittedText" > {
        this.state.submitted ?
        this.state.inputText : ''
      } < /p> <
      p id = "submittedDate" > {
        this.state.submitted ?
        this.state.date.toLocaleTimeString() : ''
      } < /p>

      <
      /div>
    )
  }
}



ReactDOM.render( < App / > , document.getElementById('root'));
<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 id="root"></div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.