Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass props from one class to another in React.js

I'm very new to React. I'm practicing by creating a very simple nine grid box, where a user can select what color they want to use at the moment by using a dropdown menu. The only thing is, I can't quite figure out how to pass the variable from the class that contains it (ColorPicker) to the class that contains the grids (Box). Can anyone give me some pointers on how to do this?

I'm still getting used to passing props to other classes.

Here's a link to the CodePen: http://codepen.io/anfperez/pen/RorKge

Here's my code

//this displays the color selections for the boxes: red, green, and blue
var ColorPicker = React.createClass({

handleChange: function(e) {
    var newColor = e.target.value;
    this.props.onChange(color);

},

render: function() {
    
return (
    <div>
        <select id="pick-colors" onChange={this.handleChange}>
            <option value="red">
                Red 
            </option>

            <option value="green">
                Green 
            </option>

            <option value="blue">
                Blue 
            </option>

        </select>

    </div>
    )
}
});

//contains the boxes that will eventually change color
var Box = React.createClass({
getInitialState: function() {
    return {
      //boxes are initially white
        color: 'white'
    };
},

    changeColor: function(newColor) {
        var newColor = this.state.color;
        this.setState({
            color: newColor
        });

    },

render: function() {
    return (
    <div >
    <div className='box' style={{background:this.state.color}} onClick={this.changeColor}> 
    </div>
    </div>
    );
}
});
like image 653
Leia_Organa Avatar asked Nov 17 '16 18:11

Leia_Organa


2 Answers

Props in React get passed from the parent to the child. For instance, If you have a parent class which renders a child class, the parent class can now pass props to the child class. Here is an example.

class Parent extends React.Component {
    render() {
        return (
            <Child example="foo" />
        )
    }
}

class Child extends React.component {
    render() {
        return (
            <h1>{this.props.example}</h1>
        )
    }
}

The parent class renders the child class. The parent class passes a prop to child called example. In child you can have access to the value of example by calling this.props.example

like image 111
Chaim Friedman Avatar answered Oct 08 '22 21:10

Chaim Friedman


Instead of rendering to the DOM 10 times, you should render one main component that wraps each of the others. You can reuse components inside other components and pass props down.

like image 42
Rico Rojas Avatar answered Oct 08 '22 23:10

Rico Rojas