Reputation: 2003
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
Upvotes: 1
Views: 5179
Reputation: 999
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>
);
}
Upvotes: 5