javascript - Rendering React Components based on array object id -


i have data called channels array containing objects:

channels : [   { name:'tv100',number:'100'},   { name:'tv200',number:'200'} ] 

my components in react:

channelcontainer:

export default class channelcontainer extends react.component {     constructor(props) {         super(props)         this.state = {             channels: '',             selectedchannel: ''         }     }      componentdidmount() {         let channel_data = [{ name: 'tv100', number: '100' }, { name: 'tv200', number: '200' }];         this.setstate = { channels: channel_data }     }      render(){         return (             <div classname="tv">                 <tvguide channel={this.state.channels} />                 <tvview channel_nr={this.state.selectedchannel} />             </div>         );     } } 

tvguide component:

const tvguide = (props) => {     return (         <div classname="tvguide_container">             <ul>                 {props.channel.map((number, index) => {                     return(                         <li key={index}>                             <a> {number}</a>                         </li>                     )                    })                 }             </ul>         </div>     );   } 

tvview component:

const tvview = (props) => {     return (         <div>             <h1>{props.channel.name}</h1>         </div>     ) } export default tvview 

when user click on 1 of links in tvguide component send props data tvview component can render name of channel. best way go forward in react?

from channelcontainer pass in onclick handler tvguide called channel clicked on, , call setstate in container, thereby rerendering tvview.

class channelcontainer extends react.component {      // ...      onguideclick = (channel) => {         this.setstate({             selectedchannel: channel         })     }      render(){         return (             <div classname="tv">                 <tvguide onclick={this.onguideclick} channel={this.state.channels} />                 <tvview channel_nr={this.state.selectedchannel} />             </div>         );     } }   const tvguide = (props) => {      return (         <div classname="tvguide_container">             <ul>                 {props.channel.map((channel) => {                     const onclick = () => {                         props.onclick(channel);                     }                     return(                         <li onclick={onclick} key={channel.number}>                             <a>{channel.name}</a>                         </li>                     )                 })                 }             </ul>         </div>     ); } 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -