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!