I'm finally switching from jQuery to ReactJS, which is causing me to rethink some of the fundamentals.
In this case, I have a dashboard with three views and three corresponding navigation buttons. When I click one of these buttons, I want to show the corresponding view and hide the other two views.
Programmatically speaking, this is easy, but I want to make sure I'm "thinking in React" and learning the correct methodology.
This code works but seems bloated. Any advice?
var Views = React.createClass({
changeView: function (event) {
var view = $(event.target).text();
if(view == 'Audience') {
this.setState({
displayAudience: true,
displayMetrics: false,
displaySettings: false
})
}
if(view == 'Metrics') {
this.setState({
displayAudience: false,
displayMetrics: true,
displaySettings: false
})
}
if(view == 'Settings') {
this.setState({
displayAudience: false,
displayMetrics: false,
displaySettings: true
})
}
},
getInitialState: function () {
return {
displayAudience: true,
displayMetrics: false,
displaySettings: false
};
},
render: function () {
return (
<div className="table">
<div className="cell top col-15">
<ul className="navigation">
<li onClick={this.changeView}>Audience</li>
<li onClick={this.changeView}>Metrics</li>
<li onClick={this.changeView}>Settings</li>
</ul>
</div>
<div className="cell top col-85 view">
{ this.state.displayAudience ? <Audience /> : null }
{ this.state.displayMetrics ? <Metrics /> : null }
{ this.state.displaySettings ? <Settings /> : null }
</div>
</div>
);
}
});
A library like react-router would be a more full featured solution but might be overkill for your use case. Your example can be simplified a fair bit by remembering that react components are basically javascript objects.
var Views = React.createClass({
changeView: function (viewComponent) {
this.setState({
currentView: viewComponent
});
},
getInitialState: function () {
return {
currentView: <Audience/>
};
},
render: function () {
return (
<div className="table">
<div className="cell top col-15">
<ul className="navigation">
<li onClick={this.changeView.bind(null, <Audience/>)}>Audience</li>
<li onClick={this.changeView.bind(null, <Metrics/>)}>Metrics</li>
<li onClick={this.changeView.bind(null, <Settings/>)}>Settings</li>
</ul>
</div>
<div className="cell top col-85 view">
{this.state.currentView}
</div>
</div>
);
}
});