Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional rendering of multiple elements

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

like image 567
MasterWilliams Avatar asked Feb 01 '26 09:02

MasterWilliams


1 Answers

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.

like image 151
Chan Youn Avatar answered Feb 03 '26 22:02

Chan Youn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!