简体   繁体   中英

Complex conditionals for classNames in React

I am currently re-writing one of my Web applications (made using jQuery and JavaScript) to use React.js instead.

I am having a little trouble figuring out how to render classNames when working with a complex conditional statement.

I have two states called userChoseToMeetAlien and cupAndSaucerHaveArrived in my main component class called AppContainer.

The initial state of the userChoseToMeetAlien and cupAndSaucerHaveArrived booleans are set to false as follows.

constructor(props) {
        super(props);
        this.state = {
        userChoseToMeetAlien: false,
        cupAndSaucerHaveArrived: false
    };
}

I have a stateless component called CupAndSaucer and these states (mentioned above) are passed in as properties.

I would like to add different classes to the HTML (rendered in CupAndSaucer ) depending on the values of these properties.

Here is the pseudocode of how I would like things to work:

 if(props.userChoseToMeetAlien is true AND props.cupAndSaucerHaveArrived is false) then
     add the move_animation class   
 else if(props.userChoseToMeetAlien is false AND props.cupAndSaucerHaveArrived is true)
     add the full_position class
 else 
     //both properties are false
     should have no classes
 end

Here is my CupAndSaucer component where I have attempted to add the classes. As you can see it is not ideal as the full_position class is added when both props.userChoseToMeetAlien and props.cupAndSaucerHaveArrived are false.

const CupAndSaucer = function(props) {  
    return (<div id="cup_and_saucer_container" 
               className={((props.userChoseToMeetAlien === true  && props.cupAndSaucerHaveArrived === false) ? 'move_animation' : 'full_position')}>    
        </div>
    );

}

I'd appreciate any help. Thanks

Try this awesome library https://github.com/JedWatson/classnames Something like this:

import cn from 'classnames';

const CupAndSaucer = function(props) { 

    const className = cn('some-default-class', {
      'move_animation': (props.userChoseToMeetAlien === true  && props.cupAndSaucerHaveArrived === false),
      'full_position': (props.userChoseToMeetAlien === false  && props.cupAndSaucerHaveArrived === false)
    });
    return (<div id="cup_and_saucer_container" 
               className={className}>    
        </div>
    );

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM