Reputation:
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 it's allowed to have my own property in react component.
Upvotes: 3
Views: 548
Reputation: 28654
You can have such a property but you need to keep in mind that when you store some value in such a property react will not re render a component - so if you are using that value in render, you might not see the updated value. With setState
that's not the case. If you have something in state and then update the state react will re render the component.
There was some guideline on what to put in state (from Dan Abramov), short summary here:
Upvotes: 1
Reputation: 6239
I think you're referring to having the videoList
stored onto the Component instance?
You could store the list of videos on state, but it seems unecessary to do this and I would simplify VideoList
to be a stateless functional component that renders the list of videos passed in as a prop:
const VideoList = ({ videos }) => (
<ul className="collection">
{videos.map(video => <VideoListItem video={video} />)}
</ul>
);
The official docs don't actually explain the syntax above, but it is basically syntactic sugar for a React component with no state, that just accepts props
. The ({ videos })
syntax is ES6 Destructuring in action. The VideoList
component receives props
and this syntax extracts props.videos
as a variable on the component.
Additionally, as you're rendering a list of items, you should provide some kind of unique key for each VideoListItem
as you render it e.g.
<VideoListItem key={video.id} video={video} />
Upvotes: 0
Reputation: 4220
Well, it is ok to have your own property in your react component. No one will blame you.
But don't forget to ship it with propType, it will save you lot time (catch bugs with type checking).
reference: https://facebook.github.io/react/docs/typechecking-with-proptypes.html
Upvotes: 0