Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing data in React

I'm actually new to React, and can't choose, what is the best way to store data in a situation like this: I have a form with some inputs, and I need to do some actions with all data from these inputs on submit. All inputs are stored in one Component. So, I need to get all the data only on submit. And now I'm trying to choose the best way to store this data. I see 2 ways:

  • Storing data in the state. But as React Docs describes:

    "Only data which need to render may store in the state."

    But I don't need this data for render, I need to work with this only on submit.

  • Storing as class variables. It looks good for me, because when i using state, i need to call setState(), which trigger render(which i don't need), or this.state.data = ....But React Docs says that:

    "You may change state directly only in constructor."

So, which of these ways are better and why?

like image 480
Vanya Makhlinets Avatar asked Mar 07 '23 02:03

Vanya Makhlinets


1 Answers

I think you're overthinking it, just stick with controlled components and manage your form data through state.

However, if you really don't want to use controlled components because you don't want the render method to be called then you don't have to.

This is because form elements work a little bit differently from other DOM elements in React, because in HTML, form elements such as <input>, <textarea>, and <select> naturally maintain their own state and update it based on user input. See official forms docs.

And React doesn't take that away from you. This means that you can make use of forms the same way you would with vanilla JS.

Also worth mentioning that in React world this way of leaving data to be purely handled by the DOM rather than handling it with a React Component is known as Uncontrolled Component.

Implementation

As far as how this would look in practise, I can think of two ways that you can do this, one would be with refs:

handleSubmit = (e) => {
  e.preventDefault();
  console.log(this.input.value); // whatever you typed into the input
}

render() {
  return (
    <form onSubmit={this.handleSubmit}>
      <input type="text" name="name" ref={input => this.input = input} />
      <input type="submit" value="submit" />
    </form>
  );
}

Another way would be through an event object:

handleSubmit = (e) => {
  e.preventDefault();
  console.log(e.target.name.value); // whatever you typed into the input
}

render() {
  return (
    <form onSubmit={this.handleSubmit}>
      <input type="text" name="name" />
      <input type="submit" value="submit" />
    </form>
  );
}
like image 167
linasmnew Avatar answered Mar 19 '23 13:03

linasmnew