I'm trying to learn how to use props in react js with making a comment post, but I can't seem to make the default profile image, from the ProfilePicture component render in the Comment component. Please help (°Ω°)/, thanks in advance.
const ProfilePicture = (props) => {
return (
<div>
<img
className="ProfilePicture"
src={props.image.pfpUrl}
alt={props.image.name}
height={100}
width={100}
/>
</div>
)
};
// user's comment
const comment = {
image: {
name: "Default Profile Image",
pfpUrl: 'https://static.vecteezy.com/system/resources/thumbnails/009/292/244/small/default-avatar-icon-of-social-media-user-vector.jpg'
}
}
const Comment = (props) => {
return (
<div>
<ProfilePicture image={comment.pfpUrl}/>
</div>
)
}
ReactDOM.render(
<Comment image={comment.image} />,
document.getElementById('root')
);
CodePudding user response:
You're passing a prop called image
here:
<Comment image={comment.image} />
But nowhere in the <Comment>
component do you use that prop. Instead, you use comment
directly:
<ProfilePicture image={comment.pfpUrl}/>
And comment
has no property called pfpUrl
. If you want to use the object directly, use the correct property:
<ProfilePicture image={comment.image.pfpUrl}/>
(And of course remove the prop since it's unused.)
If you want to use the prop, use the prop:
<ProfilePicture image={props.image}/>
CodePudding user response:
You just need to be more careful with props. Typescript would help you a lot to avoid such errors.
const ProfilePicture = ({image}) => {
return (
<div>
<img
className="ProfilePicture"
src={image.pfpUrl}
alt={image.name}
height={100}
width={100}
/>
</div>
)
};
// user's comment
const comment = {
image: {
name: "Default Profile Image",
pfpUrl: 'https://static.vecteezy.com/system/resources/thumbnails/009/292/244/small/default-avatar-icon-of-social-media-user-vector.jpg'
}
}
const Comment = ({image}) => {
return (
<div>
<ProfilePicture image={image}/>
</div>
)
}
ReactDOM.render(
<Comment image={comment.image} />,
document.getElementById('root')
);