SHUMAcupcake SHUMAcupcake - 3 years ago 90
React JSX Question

Rendering React Components based on array object id

I have some data called channels which is an 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 a user click on one of the links in TvGuide component I would like to send props data to TvView component so it can render the name of the channel. What is the best way to go forward with this in react?

Answer Source

From ChannelContainer I would pass in a onClick handler to TvGuide which would be called with the channel clicked on, and this would call setState in the container, thereby rerendering your 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>
    );
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download