6

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.
2
  • 3
    Yes, this is a good pattern. Commented Jun 10, 2017 at 17:37
  • As far as I know, this is the ideal way to use controlled inputs Commented Jun 27, 2019 at 14:37

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

Comments

0

building off of @frontsideair's answer, you could do something like the following using https://github.com/NullVoxPopuli/react-state-helpers

import React, { Component } from 'react';
import stateWrapper from 'react-state-helpers';

class App extends Component {
  render() {
    const { 
      mut, 
      values: { name } 
    } = this.props;

    return <InputComponent name={name} handleChange={mut('name')} />;
  }
}

export default stateWrapper(App)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.