Can someone provide a correct explanation for the managed input references and use case for the state variable in react?

I went through the response documents, about controlled and uncontrolled components. I created a simple use case where I want the user to only enter uppercase values ​​in an input field.

In the first case, I used 'ref' with 'onChange' to achieve this and the object's global property to grab the dom node. Here's the code for that -            https://jsfiddle.net/69z2wepo/78064/

class Nikhil extends React.Component {
   constructor(props){
      super(props);
        this.field = {
            input: ''
        };
      }
    foo() {
       this.y = this.field.input;
       this.y.value = this.y.value.toUpperCase();
     }
    render() {
      return (
        <div>
           <input ref={ node => this.field.input = node } onChange={ this.foo.bind(this) }/>
        </div>
       );
     }
   }

ReactDOM.render(<Nikhil/>,container);

      

In the second case, I used the value and state property with'onChange. Here's the code for that - https://jsfiddle.net/69z2wepo/78066/

class Nikhil extends React.Component {
  constructor(props){
    super(props);
    this.state = {
        input: ''
    };
  }
  foo(e) {
    this.setState({ input: e.target.value.toUpperCase() });
  } 
  render() {
    return (
      <div>
        <input value= { this.state.input } onChange={ this.foo.bind(this) }/>
      </div>
    );
  }
}

ReactDOM.render(<Nikhil/>,container);

      

The docs say:

 With a controlled component, every state mutation will have an 
 associated handler function. This makes it straightforward to 
 modify or validate user input. For example, if we wanted to enforce 
 that names are written with all uppercase letters, we could write 
 handleChange as:

 handleChange(event) {
  this.setState({ value: event.target.value.toUpperCase()} );
 }

      

Well, I can check the user input even if I am not using state, rather than syncing the prop value with the state like in the first example above.

  • So, certain validation of user input can be done without using state at all?

  • Can you explain why one approach is better than the other?

  • What does "the only source of truth" mean, and why is it so important?

In both cases, I am using the global variable of the component, which is an object and can be accessed throughout the component.

  1. Also why should I unnecessarily use value = {this.state.input} in example 2, because that will trigger a render on every key press, whereas in case 1 render is called only once. So isn't the performance in case 1 better than 2?

Also from the docs:

 To write an uncontrolled component, instead of writing an 
 event handler for every state update, you can use a ref to get 
 form values from the DOM

      

Well, I need to write an event handler like "onChange" even when using "ref" to validate user input at runtime, as in case 1. So is it okay to use an event handler with "ref"?

Use register for state variable. In my opinion, the only case where I have no choice but to use a state variable is when I need to dynamically update the view. Because this.setState () calls the render every time it starts. Here's the code for that - https://jsfiddle.net/69z2wepo/78068/

class Nikhil extends React.Component {
  constructor(props){
  super(props);
    this.state = {
        input: ''
    };
  }
  foo(e) {
    this.setState({ input: e.target.value });
  }
  render() {
    return (
    <div>
      <input onChange={ this.foo.bind(this) }/>
        <p>{ this.state.input }</p>
    </div>
  );
 }
}

ReactDOM.render(<Nikhil/>,container);

      

I would be grateful if someone can clarify all three examples and improve my understanding of the above concepts.

+3


source to share


2 answers


  • Use the ref method to create a new collection item via submit. Let's say you have a MongoDB collection called cars

    . If you want to add a car through a submission form, you must use the ref method.

  • Use the value (onChange) method to edit an existing item. Let's say you want to change the price of your car collection for a specific car. You are mirroring the state with the input, so by typing you will also change the state at the same time.



React the official docs recommend the second method, but you can't change the value of an element that doesn't exist, so in these cases the first method is appropriate.

+2


source


According to React Docs - https://facebook.github.io/react/docs/refs-and-the-dom.html :

Don't overuse links

Primarily you can use links to "do things" in your application. If so, think and think about where the state should belong in the component hierarchy. It often becomes clear that the proper place for "own" this state is at a higher level in the hierarchy.

In rare cases, you may need to access the child DOM node from the parent component. This is generally not recommended as it breaks the encapsulation of the components, but it can sometimes be useful for triggering focus or measuring the size or position of a child DOM node.



I think the general idea is that if you are using React you should use whichever reacts best, i.e. state manipulation with setState.

+1


source







All Articles