Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stateless React components with controlled input

Currently to make controlled inputs work inside Stateless React components I am wrapping the stateless component inside a Sate full component.

For example,

const InputComponent = (props) => {
  return (
    <input value={props.name} onChange={props.handleChange} />
  );
}

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: 'Tekeste'
    };
    this.handleChange = this.handleChange.bind(this);
  }
  handleChange(event) {
    this.setState({
      name: event.target.value
    });
  }
  render() {
    return (
      <InputComponent name={this.state.name} handleChange={this.handleChange} />
    );
  }
}

What I would like to know is a couple of things.

  1. Is this a good pattern?
  2. If not how can I achieve my goal i.e to have controlled inputs inside stateless components.
like image 970
Tekeste Kidanu Avatar asked Jun 10 '17 17:06

Tekeste Kidanu


1 Answers

Since the InputComponent receives its value and the callback to modify it from its parent, it's a controlled input without a state. It's a perfectly good pattern, you can also make it even simpler using ES7 class properties like this:

class App extends React.Component {
  state = {
    name: 'Tekeste'
  };

  handleChange = (event) => {
    this.setState({
      name: event.target.value
    });
  }

  render() {
    return (
      <InputComponent name={this.state.name} handleChange={this.handleChange} />
    );
  }
}

If you're using create-react-app, it's already supported out-of-the-box.

Also, you can rename the props of controlled input to value and onChange as they are more conventionally used.

like image 123
frontsideair Avatar answered Sep 30 '22 14:09

frontsideair