Search code examples
reactjsstateeventhandler

How to add input text event handler in react


I was enrolled to a react course in udemy and there is an assigment. There the solution was given but it seems like react library files have been updated so the code needs change for state and evenhandler. Here I am posting the code and the answer I found just in case if anyone needs answer.

    import React, { Component } from 'react';
import './App.css';

import UserInput from './UserInput/UserInput';
import UserOutput from './UserOutput/UserOutput';

class App extends Component {
  state = {
    username: 'jkr'
  }

  usernameChangedHandler = (event) => {
    this.setState({username: event.target.value});
  }

  render() {
    return (
      <div className="App">
        <ol>
          <li>Create TWO new components: UserInput and UserOutput</li>
          <li>UserInput should hold an input element, UserOutput two paragraphs</li>
          <li>Output multiple UserOutput components in the App component (any paragraph texts of your choice)</li>
          <li>Pass a username (of your choice) to UserOutput via props and display it there</li>
          <li>Add state to the App component (=> the username) and pass the username to the UserOutput component</li>
          <li>Add a method to manipulate the state (=> an event-handler method)</li>
          <li>Pass the event-handler method reference to the UserInput component and bind it to the input-change event</li>
          <li>Ensure that the new input entered by the user overwrites the old username passed to UserOutput</li>
          <li>Add two-way-binding to your input (in UserInput) to also display the starting username</li>
          <li>Add styling of your choice to your components/ elements in the components - both with inline styles and stylesheets</li>
        </ol>
        <UserInput 
          changed={this.usernameChangedHandler} 
          currentName={this.state.username} />
        <UserOutput userName={this.state.username} />
        <UserOutput userName={this.state.username} />
        <UserOutput userName="Max" />
      </div>
    );
  }
}

export default App;

Solution

  • Here the code for state and event handler needs modification as following

        class App extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          username: 'jkr'
        };
       this.usernameChangedHandler=this.usernameChangedHandler.bind(this);
        
      }
    
    
    
    usernameChangedHandler(event)  {
        this.setState( { username: event.target.value});
      }
    

    This would do

    Courtesy: https://reactjs.org/docs/forms.html https://reactjs.org/docs/hooks-state.html