Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle active state on different tabs using react inline styles

Tags:

reactjs

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!

like image 392
dydy00 Avatar asked Apr 07 '26 03:04

dydy00


1 Answers

you can use state for this type of implementations. a brief implementation is like below :

  1. 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)
    }
    
  2. 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>
      )
    }
    
  3. 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 :

  • State
  • The Binding
  • Event Handling
like image 158
Amir Mohammad Moradi Avatar answered Apr 08 '26 19:04

Amir Mohammad Moradi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!