How can I take a input from user and change it with setState?

Viewed 71
constructor() {
  super();
  this.state = {
    name: "",
    name1: "",
  };
}

change = () => {
  this.setState({ name: this.state.name1 });
};

handleChange = (e) => {
  this.setState({ name1: e.target.value });
};

render() {
  return (
    <div>
      <input
        type="text"
        placeholder="Enter your name"
        onChange={this.handleChange}
      ></input>
      <button onClick={this.change}>Click Me!</button>
      <h4>Hello! {this.state.name}</h4>
    </div>
  );
}

This is what I did but feels like it is nonsense on actual webpage even it works. Is there a better way to take input from user?

4 Answers

Why you need name and name1 in state. Just name should be fine. See the below code if that helps

I am not sure why you handle a event in button. May you can use a form with OnSubmit.

import React from "react";
import "./style.css";

export default class App extends React.Component {
  constructor() {
    super();
    this.state = {
      name: "",
    };
  }

  render() {
    return (
      <div>
        <input
          type="text"
          placeholder="Enter your name"
          onChange={(e) => this.setState({name: e.target.value})}
        />
        <button>Click Me!</button>
        <h4>Hello! {this.state.name}</h4>
      </div>
    );
  }
}

Your onChange in the input would be

onChange={event => this.handleChange(event)}

And for the button it would be

onChange{() => this.change()}

We would not require 2 states for the name but we would need one variable to store the name and second variable to let the component know that name has been update. We need the second variable because on button click only the name has to be updated(as per the code mentioned).The component would re-render when a state is updated. Below code might be helpful.

class Content extends React.Component {
  constructor(){
    super()
    this.state = {
        name: "",
    }
    this.name=''
}

change = () => {
    this.setState({name: this.name})
}

handleChange = (e) => {
    this.name=e.target.value
}

render(){

    return(
        <div>
            <input type = "text" placeholder="Enter your name" onChange={this.handleChange}></input>
            <button onClick={this.change}>Click Me!</button>
            <h4>Hello! {this.state.name}</h4>
        </div>
    )
}}

Here is a version with React Hooks:

import React, { useState } from 'react';

export default function App() {
  const [name, setName] = useState('');

  const handleNameChange = (e) => {
    const nameInput = e.target.value;
    setName(nameInput);
  };

  return (
    <div>
      <input
        type="text"
        placeholder="Enter your name"
        onChange={(e) => handleNameChange(e)}
      ></input>
      <button>Click Me!</button>
      <h4>Hello! {name}</h4>
    </div>
  );
}
Related