Hey there React developers! Wanna Know how to add className dynamically with some really cool example? Then you are in right place. Go through the post to understand in-depth.
What is React?
React is a JavaScript library for building user interfaces.
Click here to know more.
What is React Ref?
Refs provide a way to access DOM nodes or React elements created in the render method.
Click here to know more.
Let's consider an example where you create a list of buttons using the map function.
const buttonsArray = ['Button 1', 'Button 2' , 'Button 3']
buttonsArray.map((button)=>{
return(
<button>{button}</button>
)
}
)
Now let's create ref to list of buttons. I have created refs as “callback refs”
const buttonsArray = ['Button 1', 'Button 2' , 'Button 3']
buttonsArray.map((button,index)=>{
return(
<button ref={a => this.buttonElement[index] = a} >{button}</button>
)
}
)
Along with this, you need to declare "this.buttonElement" inside the constructor.
constructor(props) {
super(props);
this.buttonElement = [];
};
Now starts the magic, let's consider you have written all the necessary CSS. From the list of buttons, you want the first button to be active on page loading. How to make it? Check the below code...
considering "active" is the CSS className
componentDidMount() {
this.buttonElement[0].className = this.buttonElement[0].className+"active";
}
You can also add different styles for all 3 buttons...
componentDidMount() {
this.buttonElement[0].className = this.buttonElement[0].className+"active";
this.buttonElement[1].className = this.buttonElement[1].className+"foo";
this.buttonElement[2].className = this.buttonElement[2].className+"bar";
}
Explaination:
'this.buttonElement' is a list of buttons so in order to make the first element to be active we added 'active' className to index=0 element.
Extra:
You can also make a click event to the first button.
componentDidMount() {
this.buttonElement.click();
}
If you have need of the above code, then you don't need to add className, because the click event in-turn make the button to active and CSS will take care of that condition.
Here just to make the code snippet understandable, I have implemented using a button. You can make use of any HTML element or any event.
Thank You,
Top comments (5)
Thanks!
Class components 🤮
You can make this in functional component also....
This is unusable,i cant add class with refs on socket event at all.I ask myself if we cant add simple class on some socket event ,why refs exists?
Right ??
Vue let's you do that.
this.$refs['some-ref'].$el.classList.add('some-class')