Why is my text not changing as I'm writing text to the input tag in React

Viewed 56

My code from App.js. The idea is that when you enter text in input the screen should be updated accordingly. For some reason set state isn't working and I don't know why.

import React, { Component } from 'react';
import UserOutput from './Components/UserOutput';
import UserInput from './Components/UserInput';
class App extends Component {
  state = {
    username: 'Adib',
  };
  changeUsername = (event) => {
    this.setState({
      username: event.target.value,
    });
  };
  render() {
    return (
      <div className="App">
        <UserInput changed={this.changeUsername} />
        <UserOutput name={this.state.username} />
      </div>
    );
  }
}

export default App;

My code from useroutput.js

import React from 'react';

const userOutput = (props) => {
  return (
    <div>
      <p>Username: {props.name}</p>
      <p>Hello {props.name}</p>
    </div>
  );
};

export default userOutput;

My code from userinput.js

import React from 'react';

const userInput = (props) => {
  return <input type="text" onChanged={props.changed} />;
};

export default userInput;

2 Answers

You are using onChanged as the name of the event action on the input field in the userInput Component. replace it with

return <input type="text" onChange={props.changed} />;

Your UserInput component is using an onChanged event which is not a valid event in React, try using onChange instead.

import React from 'react';

const userInput = (props) => {
  return <input type="text" onChange={props.changed} />;
};

export default userInput;
Related