1

I am learning React and below one is sample code I am trying out. I am able to render this component and able to type in characters in input field without any handleChange() method ? Is this fine ? because what I know is, in order to make input fields available for typing, we need to add handleChange method something like below

handleChange(e) {
    this.setState({ [e.target.name]: e.target.value });
}

import React from "react";

class StudentForm extends React.Component {
  constructor() {
    super();
  }

  render() {
    return (
      <div>
        <form>
          <h1>Student Form</h1>
          <input type="text" name="firstname"></input>
        </form>
      </div>
    );
  }
}

export default StudentForm;
Mr bond
  • 133
  • 2
  • 13
  • It's controlled vs uncontrolled component. You can check the response here : components.https://stackoverflow.com/questions/42522515/what-are-controlled-components-and-uncontrolled-components – Gaël S Sep 19 '19 at 13:10

3 Answers3

1

handleChange is for setting the state value.

without onChange handler you can type in but your value is not getting stored anywhere.

For example, if you try to access your state this.state.firstname you will always get undefined.

You should have controlled component. Which is a simple and cleaner way access and store value in state.

To make your component controlled, you should have value and onChange props on input,

<input type="text" name="firstname" value={this.state.firstname} onChange={this.handleChange.bind(this)}></input>
ravibagul91
  • 20,072
  • 5
  • 36
  • 59
0

Yes, consider the following

<input type="text" name="firstname" />

This is an uncrontrolled input which means React doesn't now about it's value nor how to change it. To make an input controlled you need to explicitly specify the value and onChange properties to bind this input to React's state

const Input = () =>{
    const [value, setValue] = useState('')

    return <input value={value} onChange={e => setValue(e.target.value)} />
}

Now the input is fully controlled by React, which provides the value it must print and a way to change it

Dupocas
  • 20,285
  • 6
  • 38
  • 56
0

After making below changes, I made this input element as controlled element and now I am not able to type in anything without using onChange handler.

import React from "react";

class StudentForm extends React.Component {
  constructor() {
    super();
    this.state = {
      firstname: ""
    };
  }

  render() {
    return (
      <div>
        <form>
          <h1>Student Form</h1>
          <input
            type="text"
            name="firstname"
            value={this.state.firstname}
          ></input>
        </form>
      </div>
    );
  }
}

export default StudentForm;
Mr bond
  • 133
  • 2
  • 13
  • 1
    This is because you have binded the state value to your input, now your input need onChange handler or you can make it as `defaultValue`. – ravibagul91 Sep 19 '19 at 13:21