Search code examples
javascriptreactjssemantic-ui-react

How to use a condition in react component within semantic ui dropdown menu component


I would like to build a little dropdown menu (I'm using semantic-ui-react). But in my case I need a condition depending part of this menu.

This is what I came up with, but it won't work, as it would have to be wrapped. So how should I create this dropdown menu in a correct way to get two menu subblocks with header, divider and items if the ifThisIsTrue has true value?

render() {
    const ifThisIsTrue = true
    return (
        <Dropdown icon='cogs' className='icon settings'>
            <Dropdown.Menu>
                {
                    ifThisIsTrue &&
                        <Dropdown.Header icon='cogs' content='Label' />
                        <Dropdown.Divider />
                        <Dropdown.Item value='default'>Standard</Dropdown.Item>
                        <Dropdown.Item value='something'>Something</Dropdown.Item>
                        <Dropdown.Item value='else'>Else</Dropdown.Item>
                }

                <Dropdown.Header icon='cogs' content='Edit' />
                <Dropdown.Divider />
                <Dropdown.Item>Delete</Dropdown.Item>
                <Dropdown.Item>Edit</Dropdown.Item>
            </Dropdown.Menu>
        </Dropdown>
    )
}

Solution

  • Wrap the conditional elements in an array (separated by commas, of course). You'll need to give each item a key property. React will take care of the rest.

    const Component = ({ifThisIsTrue}) => (
      <ul>
        <li>One</li>
        { ifThisIsTrue && [
            <li key="2">Two</li>,
            <li key="3">Three</li>
          ]
        }
      </ul>
    );
    
    ReactDOM.render(<Component ifThisIsTrue={Math.random() > 0.5}/>, document.querySelector('div'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
    <div></div>