how do I pass data upwards in reactjs?

- 1 answer

Ad

Say I have an app with some path app -> taskbar -> button -> modal -> textfield. I want the textfield to be some setting a user inputs and is used elsewhere in the app, maybe app -> differentButton -> differentModal displays this user setting for example

I'm brand new to react, but it seems data can only go downwards through props, right? Is it expected that I store this state externally in a db? I don't mind doing that, but it seems like there should be an easy way to do this that I'm overlooking?

Ad

Answer

Ad

You can store the state in the parent component and pass not only the value, but also the function that modifies the value to the child. Eg:

const App = React.createClass({
    getInitialState () {
        return {
            name: 'Dave'
        };
    },
    render () {
        return (
            <div>
                <MyComponent name={this.state.name} changeName={this.onChangeName} />
            </div>
        )
    },
    onChangeName (name) {
         this.setState({ name });
    }
});

const MyComponent = React.createClass({
    propTypes: {
         name: React.PropTypes.string,
         changeName: React.PropTypes.func.isRequired
    },
    render () {
        return (
            <div>
                <input value={this.props.name} onChange={this.props.changeName} />
            </div>
        );
    }
});
Ad
source: stackoverflow.com
Ad