DEV Community

loading...

Discussion on: Fast & easy... React states management in one function

Collapse
mgtitimoli profile image
Mauro Gabriel Titimoli

You can try this alternative instead that doesn't require you to add any instance method (methods declared using arrow fns).

import React from "react";

// you can move this fn to an independent module and import it here
const setState = (component, updateState) => params =>
  component.setState(updateState(params));

const setName = event => prevState => ({
  ...prevState,
  name: e.target.value
}); 

export default class App extends Component {
  state = {
    name: ""
  };

  render() {
    return (
      <div>
        <input
          placeholder="insert your name" value={this.state.name} 
          onChange= {setState(this, setName)} />
      </div>
    );
  }
};