Reputation: 149
I want ro render 3 additional buttons if the current user is the user that created the group i'm in at the moment, so i tried someting like this :
render(){
let adminButtons;
if (this.state.groupData && this.props.user.id){
if(this.state.groupData.owner === this.props.user.id){
adminButtons = {
<CustomButton>Add Quiz</CustomButton>
<CustomButton>Drafts</CustomButton>
<CustomButton>Delete Group</CustomButton> };
}
else{
adminButtons = <div/>;
}
}
}
return(
<div className='group-page'>
<div className='group-controls'>
<div className='admin-buttons'>
{adminButtons}
</div>
</div>
</div>
)}
But this implementation raises a compiler error , how could i change up the code in order to make it work? JSX experssion must have one parent element , is the error i'm getting
Upvotes: 3
Views: 1828
Reputation: 892
The short answer is you can wrap your components in a React.Fragment.
<>
<CustomButton>Add Quiz</CustomButton>
<CustomButton>Drafts</CustomButton>
<CustomButton>Delete Group</CustomButton>
</>
As per the docs:
A common pattern in React is for a component to return multiple elements. Fragments let you group a list of children without adding extra nodes to the DOM.
Upvotes: 4
Reputation: 21364
render() {
let adminButtons;
if (this.state.groupData && this.props.user.id){
if (this.state.groupData.owner === this.props.user.id){
adminButtons = [
<CustomButton>Add Quiz</CustomButton>,
<CustomButton>Drafts</CustomButton>,
<CustomButton>Delete Group</CustomButton> ];
} else {
adminButtons = <div/>;
}
}
return(
<div className='group-page'>
<div className='group-controls'>
<div className='admin-buttons'>
{adminButtons}
</div>
</div>
</div>
)}
Upvotes: 1
Reputation: 4217
use :
let adminButtons = null;
if (this.state.groupData && this.props.user.id){
if(this.state.groupData.owner === this.props.user.id){
adminButtons = <>
<CustomButton>Add Quiz</CustomButton>
<CustomButton>Drafts</CustomButton>
<CustomButton>Delete Group</CustomButton> };
</>
}
}
if your condition is true
the three elements will be displayed, if the condition is false
nothing will be rendered.
Upvotes: -1
Reputation: 1911
here you need minor change
adminButtons = {
<CustomButton>Add Quiz</CustomButton>
<CustomButton>Drafts</CustomButton>
<CustomButton>Delete Group</CustomButton> };
}
to
adminButtons = [
<CustomButton>Add Quiz</CustomButton>
<CustomButton>Drafts</CustomButton>
<CustomButton>Delete Group</CustomButton> };
]
Ideally JSX
need either string, null, html/jsx elements or array of either of these. you are using object, that's why you got compile errors.
Upvotes: 1