Reputation: 45
how to change color of component from clicking a button from another. I'm trying to this by setting state, but it's not possible. And in this of component SecondAnotherBox not styles in properties.
var AnotherBox = React.createClass({
boxclick: function()
{
//change from here
},
render: function()
{
return(
<div onClick={this.boxclick}> anotherbox</div>)
}
});
var SecondAnotherBox = React.createClass({//change this
render: function()
{
return(
<div> secondanotherbox</div>)
}
});
var ComplexBox = React.createClass({
render: function()
{
return(
<div>
<AnotherBox />
<SecondAnotherBox />
</div>)
}
});
ReactDOM.render(
<ComplexBox />,
document.getElementById('test')
);
Upvotes: 4
Views: 39100
Reputation: 390
You have three components
ComplexBox with AnotherBox and SecondAnotherbox.
It would look something like this in code ...
var AnotherBox = React.createClass({
render: function()
{
return(
<div onClick={this.props.onBoxClick}> anotherbox</div>);
}
});
var SecondAnotherBox = React.createClass({//change this
render: function()
{
return(
<div style={{ borderColor: this.props.color }}> secondanotherbox</div>);
}
});
var ComplexBox = React.createClass({
getInitialState: function() {
return {
color: 'blue'
};
},
boxclick: function()
{
//change from here
var newColor = this.state.color == 'red'?'blue':'red';
this.setState({
color: newColor
})
},
render: function()
{
return(
<div>
<AnotherBox onBoxClick={this.boxclick} />
<SecondAnotherBox color={this.state.color} />
</div>);
}
});
ReactDOM.render(
<ComplexBox />,
document.getElementById('test')
);
Upvotes: 2
Reputation: 1606
Why dont you try to put a state on your container ComplexBox, like that:
var AnotherBox = React.createClass({
boxclick: function()
{
//change from here
},
render: function()
{
return(
<div
onClick={this.boxclick}
style={ this.props.boxClicked === 1 ? color: blue }
>
anotherbox
</div>
)
}
});
var SecondAnotherBox = React.createClass({//change this
render: function()
{
return(
<div style={ this.props.boxClicked === 2 ? color: blue }> secondanotherbox</div>)
}
});
var ComplexBox = React.createClass({
constructor: function() {
this.state: { boxClicked: 1 }
}
render: function()
{
return(
<div>
<AnotherBox
boxClicked: this.state.boxClicked
/>
<SecondAnotherBox
boxClicked: this.state.boxClicked
/>
</div>)
}
});
ReactDOM.render(
<ComplexBox />,
document.getElementById('test')
);
Upvotes: 0
Reputation: 3072
You can do this with the +
CSS selector if you like. See a pen here
I think this is very fragile however. Slight changes to the DOM layout will break this. You are far better off using a global state manager like redux and passing this information down to your components as props.
EDIT: You can still achieve this using only react state. Another pen for demo.
Upvotes: 1