I'm coming from jQuery so I'm having issues understanding how to go about this.
I'm writing an application in React and I'm using inline styles, i.e. each component have their own styles and they're written in JS instead of CSS.
Now, I have five tabs and I want to toggle an .is-active whenever I click one of them. So on click, I have to remove .is-active from the old class, and add it to the clicked class. I'm not sure how to approach this using inline styles, because as everything is inline there are no actual classes for me to add to my tabs.
Right now, when I render each tab (which I have as a separate component) I also pass in an isActive boolean which tells the component to render with or without active classes. Code example of this :
HTML :
<Tab isActive={true} />
<Tab isActive={false} />
JS :
<div className="tab" style={(this.props.isActive !== true) ? style.tab : {...style.tab, ...style.active}}>
But I'm completely lost on how to do this onclick. Do I have to break the inline styling concept to do this, or is there a smart solution? I haven't found anything straightforward online. Thanks!
you can use state for this type of implementations. a brief implementation is like below :
suppose you have two Tabs. you should define the state on constructor like this :
constructor(props){
super(props)
this.state = {
tabs = [
{ tab1: { active: true } },
{ tab2: { active: false} }
]
}
this.tabToggle = this.tabToggle.bind(this)
}
put tab elements into the render() :
render() {
return (
<div>
{ this.state.tabs.map((tab, index) =>
<div className={'tab ' + tab.active ? 'active' : ''}>
onClick={()=>this.tabToggle(index)}>
</div>
)}
</div>
)
}
define Toggle function like this :
tabToggle(tabIndex) {
let tabs = this.state.tabs
tabs[tabIndex] = true
tabs.map((tab, index) => {
if (index !== tabIndex) tab.active = false
})
this.setState( tabs )
}
Some Refrences for parts of Code :
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With