Currently I've a component User, which renders 2 element -> username and avatar. I'm getting the username and avatar perfectly, but I want to view only the username only
Is there any way to fetch only the username element ? Not with a profile picture.
//User component
const User = ({ username, profilePic }) => {
return (
<React.Fragment>
<Avatar name='user' src={profilePic.profile.image} alt="user_image" ml="5"/>
<Heading size={'sm'} ml="5">{username.username}</Heading>
</React.Fragment>
);
};
// Content Page
{group.members.map(member => {
return <React.Fragment key={member.id}>
<User username={member.user} profilePic={member.user}/>
</React.Fragment>
})}
You could add an extra prop renderAvatar and only display the avatar if the boolean is true with conditional rendering.
const User = ({ username, profilePic, renderAvatar }) => {
return (
<React.Fragment>
{renderAvatar && <Avatar name='user' src={profilePic.profile.image} alt="user_image" ml="5"/>}
<Heading size={'sm'} ml="5">{username.username}</Heading>
</React.Fragment>
);
};
You could use it like this.
<User username={member.user} profilePic={member.user} renderAvatar={false} />
<User username={member.user} profilePic={member.user} renderAvatar={true} />
Or just create a component that only renders the Heading.
const UserWithoutAvatar = ({ username }) => {
return <Heading size={'sm'} ml="5">{username.username}</Heading>
};
One option would be to conditionally render based on whether or not profilePic is provided at all. For example:
return (
<React.Fragment>
{ profilePic ?
<Avatar name='user' src={profilePic.profile.image} alt="user_image" ml="5"/>
: null
}
<Heading size={'sm'} ml="5">{username.username}</Heading>
</React.Fragment>
);
Then if you just don't provide profilePic it will be undefined:
<User username={member.user} />
As an aside, the code seems to be generating confusion around naming. For example:
{username.username}
A property called "username" implies that it is a string representing the user's name. But in this case username is an object containing a property called username? Does that property contain a string? Or another object?
Or here:
<User username={member.user} profilePic={member.user}/>
What is member.user? Is it a username? Is it a profile pic? Somehow it's both?
Clarity is important. If what you're actually passing to the component is a user object then call it that:
<User user={member.user} />
Alternatively, if the component is expecting a literal value for username and a literal value for profilePic then pass it those values:
<User username={member.user.username} profilePic={member.user.profile.image} />
Don't confuse your semantics. Confusion leads to bugs.