Home > Net >  conditional rendering order of the elements based on props?
conditional rendering order of the elements based on props?

Time:10-03

I created a search input component and this input has an icon which I need to change the icon's align (on the left side or right side) based on different situations (it's a bootstrap input-group) so all I need to do is change the order of elements inside my div and I need a clean way to do this. I know I can use a ternary operation to conditional render my elements but this would cause to repeat the code. I'm looking for much cleaner way so any suggestions?

const SearchInput = ({onClose, onChangeValue, ...restProps}) => {
    return (
        <div className='input-group'>
            <button className='btn' type='button'> //right now its on left side...
                <i className='bi bi-search'></i>
            </button>
            <Input placeholder='Search here...' onChangeValue={onChangeValue} {...restProps} />
            {onClose && <i className='bi bi-x' onClick={onClose}></i>}
        </div>
    );
};

CodePudding user response:

My proposal

import clsx from 'clsx';
const SearchInput = ({onClose, onChangeValue, conditionProp, ...restProps}) => {
    return (
        <div className={clsx('input-group', conditionProp && 'my-order)}>
            <button className='btn' type='button'> //right now its on left side...
                <i className='bi bi-search'></i>
            </button>
            <Input placeholder='Search here...' onChangeValue={onChangeValue} {...restProps} />
            {onClose && <i className='bi bi-x' onClick={onClose}></i>}
        </div>
    );
};

In CSS

.my-order {
  flex-direction: row-reverse;
}

I like cslsx for conditional classnames, but of course I can do without it - conditionProp ? 'input-group my-order' : 'input-group'

  • Related