obiwahn obiwahn - 3 months ago 7
React JSX Question

How to change props of a child?

I am new to React. This is probably a noob question.

I want to change the "filteredFields" prop of my MeteorGriddle component when the user clicks a checkbox. My JSX:

const bookingsPage = () => {
let filteredFields = ['userName'];
const handleClick = (e) => {
if (e.target.checked) {
filteredFields = ['userEmail'];

// How to propagate this change to the MeteorGriddle?
}
}

return (
<div>
<label><input type="checkbox" defaultChecked="true" value="userEmail" onClick={handleClick}/>Email</label>

<MeteorGriddle filteredFields={filteredFields}/>
</div>
);
};

Answer

I see two ways of solving your problem.

The first and easy way to do this:

Turn your bookingsPage component into statefull component instead of functional, then you'd be able to create state inside it, and then change the state on event alongside with passing it to MeteorGriddle component.

So the code would be:

class bookingsPage extends React.Component {
    getInitialState = () => {
      filteredFields: []
    }

    handleClick = (e) => {
        if (e.target.checked) {
            const newFilteredFields = 
              [ ...this.state.filteredFields ].push('userEmail');
            this.setState({ filteredFields: newFilteredFields });
        }
    }

    render() {
    return (
        <div>
            <label>
              <input
                type="checkbox" 
                defaultChecked="true" 
                value="userEmail" 
                onClick={this.handleClick}
              />
              Email
            </label>

            <MeteorGriddle 
              filteredFields={this.state.filteredFields}
            />
        </div>
    );
  }
};

Second and harder way to do this:

Take a look on Redux. It solves a problem of data flow in React. The basic concept is that when you check you checkbox, you dispatch an action into reducer (aka your global data storage for react components), and then GriddleComponent recieves new state of your application with fresh data inside which tells him the checkbox is checked.

Say if you want me to write an example based on yours for you.