Kiran Dash
Kiran Dash

Reputation: 4956

Dynamically changing wrapper tag in React

I want to change my wrapper tag around content. Currently I am doing it like this:

{!filter && <Styled.DropdownMenu>
    {Options}
</Styled.DropdownMenu>}
{filter && <Dropdown.Menu as={CustomMenu}>
   {Options}
</Dropdown.Menu>}

Which works. But since the content Options is always going to be same. I was wondering if there is a way to dynamically change just the wrapper tag in same line without repeating the code for {Options}.

Upvotes: 0

Views: 155

Answers (2)

Nooruddin Lakhani
Nooruddin Lakhani

Reputation: 6967

Try this way

const TAG = !filter ? Styled.DropdownMenu : Dropdown.Menu;

const customMenuData = !filter ? {} : {CustomMenu};

<TAG as={customMenuData}>{Options}</TAG>

Upvotes: 1

Someone Special
Someone Special

Reputation: 13588

You can use the following instead of multiple !filter checks.

filter ? <Styled.DropdownMenu>{Options}</Styled.DropdownMenu> 
: (<Dropdown.Menu as={CustomMenu}>
       {Options}
    </Dropdown.Menu>)

Or you can create separate components and use as follows

filter ? <StyledDropDownComponent options={Options} /> : <DropDownComponent options={Options} /> 

Which makes your code cleaner.

Upvotes: 0

Related Questions