4

I'm new to React and I'd try to tinker a little bit with dataflow when using and some kind of output.

The idea is to type something in an input bar and have it shown below the bar as the user is typing. I wish to do this without stuff like Flux or Redux please. Just a simple little thing to get me familiar with dataflow.

I have a component Input

class Input extends Component {
  render() {
    return (
      <input value={this.props.inputValue} onChange={this.props.onChange} />
    );
  }
}

And a component Output

class Output extends Component {
  render() {
    return (
      <p>
        {this.props.dataSource}
      </p>
    );
  }
}

Encapsulated in a parent component which is just App

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: ''
    };
    this.onChange = this.onChange.bind(this);
  }

  onChange(event) {
    this.setState({
      value: event.target.value,
    });
  }

  render() {
    return (
      <div>
        <Input inputValue={this.state.value} onChange={this.onChange} />
        <Output dataSource={this.state.value} />
      </div>
    );
  }
}

But the Output component doesn't seem to read the value from the parent component. Also I question whether this is even the right way. Storing data in the parent component instead of the individual components themselves.

Lehren
  • 99
  • 2
  • 11
  • So to answer one of your questions, yes, you do want to store data on the parent component. This way you can pass the data between the children components and not worry about side effects when you update components that control their own state. This pattern is called 'lifting state up', check it out here in the React docs https://facebook.github.io/react/docs/lifting-state-up.html – Brett East Jun 10 '17 at 00:34
  • Hmm I copy pasted your exact code and it works fine for me. Are you getting any errors in the browser console? here's a link to a working example with your code https://www.webpackbin.com/bins/-KmERMs_TM72PP2i3bZ3 – azium Jun 10 '17 at 00:41
  • It also works for me, here it is in [codepen.io](https://codepen.io/bretteast/pen/ZyQweL?editors=1010) – Brett East Jun 10 '17 at 00:44
  • Weird. It seems to work now as well. Must have screwed something up. Thanks for the link Brett about the pattern that helps. – Lehren Jun 10 '17 at 00:50

0 Answers0