Created
May 31, 2019 06:42
-
-
Save HyunmoAhn/00a8c13656ba7663bed10036f520be84 to your computer and use it in GitHub Desktop.
Change classname on react component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import cx from 'classnames'; | |
// yarn add classnames | |
class Home extends React.Component { | |
constructor(props) { | |
super(props); | |
this.addClassName = this.addClassName.bind(this); | |
this.removeClassName = this.removeClassName.bind(this); | |
this.state = { | |
isActiveClass: false, | |
}; | |
} | |
addClassName() { | |
this.setState({ isActiveClass: true }); | |
} | |
removeClassName() { | |
this.setState({ isActiveClass: false }); | |
} | |
render() { | |
const targetClassName = cx('Btn--sm', 'Btn--primary', { 'more-class-name': this.state.isActiveClass }); | |
return ( | |
<div> | |
This is main home | |
<p className={targetClassName} >target element</p> | |
<button onClick={this.addClassName}> | |
Add Class name | |
</button> | |
<button onClick={this.removeClassName}> | |
Remove Class name | |
</button> | |
</div> | |
); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
class Home extends React.Component { | |
constructor(props) { | |
super(props); | |
this.addClassName = this.addClassName.bind(this); | |
this.removeClassName = this.removeClassName.bind(this); | |
this.state = { | |
isActiveClass: false, | |
}; | |
} | |
addClassName() { | |
this.setState({ isActiveClass: true }); | |
} | |
removeClassName() { | |
this.setState({ isActiveClass: false }); | |
} | |
render() { | |
return ( | |
<div> | |
This is main home | |
<p className={`Btn--sm Btn--primary ${this.state.isActiveClass && 'more-class-name'}`} >target element</p> | |
<button onClick={this.addClassName}> | |
Add Class name | |
</button> | |
<button onClick={this.removeClassName}> | |
Remove Class name | |
</button> | |
</div> | |
); | |
} | |
} |
Thank's :)
Thank you :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you!