I'm new to React and started this project as a sandbox to experiment with it. I implemented a main page wich has a header and some content. The content is selected on the header. I'm wondering how it stands on the react best practices and other ways it could be implemented.
On the main app, we hold as state the index of the content we want to show, and we pass to the header as a property a reference to the funtion that handles the index state, like so
class App extends Component { constructor() { super(); this.state = { cidx: 0, //content:[<Heroes/>, <Teams/>] } this.updateContent = this.updateContent.bind(this); this.getContent = this.getContent.bind(this); } updateContent(idx) { this.setState({cidx:idx}); } getContent() { //return this.state.content[this.state.cidx]; switch(this.state.cidx) { case 0: return <Heroes/> case 1: return <Teams/> } } render() { const Content = this.getContent(); return ( <div> <Header updateContent={this.updateContent} textItems={["Heroes", "Teams"]}/> {Content} </div> ); } } export default App;
Like that we can inject the content in our render function based on user interaction with the header. I used a switch statement in getContent to avoid having an array of objects in memory all the time. Is it actually better performance-wise ?
This is the header code
class Header extends Component { constructor(props) { super(props); } render() { const items = this.props.textItems.map( (item, index)=>{ return <NavItem key={index} onClick={()=>{this.props.updateContent(index)}}>{item}</NavItem> } ); return ( <div className="App"> <Navbar className="deep-purple" brand='Dota Wizard' right> {items} </Navbar> </div> ); } } export default Header;
A working version of the project is found on https://glitch.com/~absorbing-buzzard
Navbar
,Heroes
andTeams
. Even if they're not required, a short description of those can help reviewers.\$\endgroup\$