0

I have a list of domains in my UI. Every domain is a button (it can be clicked and get .active css style). The domains names are coming from server, I get them in componentDidMount() method. So I don't know the quantity of future buttons (domains) in component construct moment.

My goal is to change button style on a user click (add .active css class). The first button should be active by default. I can identify buttons by index in array. So my code looks like this:

constructor(props) {
    super(props)
    this.state = {
        domainClasses: {}
    }
}

And in componentDidMount() method:

componentDidMount() {
    this.props.domains.forEach((data, i) => {
        if (i === 0) {
            this.setState({
                ...this.state.domainClasses,
                [i]: `title active`
            });
        } else {
            this.setState({
                ...this.state.titleClasses,
                [i]: `title`
            });
        }
    });
}

I thought that setState() method will add numeric property in state object and then I can manipulate style on button classes. But it doesn't! I tested - if state doesn't contain numeric property in component construct moment it will ignore it in setState in future.

To resole it I could add every numeric property to state object in constructor method in forEach cycle but I don't know the quantity of domains until they come from server in componentDidMount...

So, my question is - how to change css classes on button click if this buttons in list and the quantity is undefined until server response?

Any help, please!

1 Answer 1

1

You are storing a possible huge state for just setting the active class for a button, why not just use something simple like activeButtonIdx

in constructor, your init state will be

this.state = {
  activeButtonIdx : 0
}

Inside ur render function, you can just give the class (Assume it is inside a map since you mentioned that you have a list of buttons)

{
  buttons.map((d, i) => <Button className={this.state.activeButtonIdx === i ? 'active title' : 'title' } onClick={() => this.setState({activeButtonIndex : i})} key={d.id}/>)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.