Can I have my own property in react component?
class VideoList extends Component {
constructor(props) {
super(props);
this.videoList = props.videos.map((video) => {
return <VideoListItem video={video} />
})
}
render() {
return (
<ul className="collection">
{this.videoList}
</ul>
)
}
}
I'm just wondering if I'm allowed to have my own property in react component.
It makes sense to have such a property, but only if you don't want to display it. Since you are rendering it, it might make sense to put it in a state. Because if you update your property - like now, you may not see the new value in the UI.
You can use the following image as a guide on what to put and not to put into state:
It was created by Dan Abramov, if I'm not mistaken.
source to share
I think you mean what videoList
is stored on the Component instance?
You can keep the list of videos by state, but that doesn't seem to need to be done, and I would simplify videoList
as a functional stateless component that displays a list of videos being passed as a prop:
const VideoList = ({ videos }) => (
<ul className="collection">
{videos.map(video => <VideoListItem video={video} />)}
</ul>
);
The official docs don't really explain the syntax above, but it's basically syntactic sugar for a stateless React component that just accepts props
. ({ videos })
ES6 Destructuring syntax in action. The component videoList
receives props
, and this syntax is retrieved props.videos
as a variable on the component.
Also, when you create a list of items, you must provide some kind of unique key for each VideoListItem
as you render it, for example
<VideoListItem key={video.id} video={video} />
source to share
The good thing is that you have your own property in your react component. Nobody will blame you.
But don't forget to send it using propType, it will save you a lot of time (catch type checking errors).
link: https://facebook.github.io/react/docs/typechecking-with-proptypes.html
source to share