Arijit Nayak
Arijit Nayak

Reputation: 21

How to set a dynamic class in react js and retrieve it in Jquery

I want to set dynamic classname in reactjs so that I can retrieve the classname for different div. Actually, I have 4 collapsible for that I have different div with the same content but functionality different. There I need to specify the different classname there so that I can retrieve the classname when I click on the particular div. And I want to retrieve that classname also inside the jquery. Please help me out in react js code.

nothing

Upvotes: 2

Views: 132

Answers (1)

Daniel Doblado
Daniel Doblado

Reputation: 2848

I created 3 dynamic divs using an array containing names and I give them a class with the respective name, to access the class you can use el.target.className, then you can use JQuery the way you want with the class (divClass), in this case I'm selecting the element.

import React, { Component } from 'react';
import { render } from 'react-dom';
import $ from "jquery";

class App extends Component {
  render() {
    const names = ['Lukas', 'Jhon', 'Ana']
    return (
      <div>
        {names.map(name => (
          <div
            className={name}
            onClick={(el) => {
              const divClass = el.target.className
              console.log($(`.${divClass}`))
            }}
          >
            {name}
          </div>
        ))}
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));

Here is a live example https://stackblitz.com/edit/react-qcheyr?file=index.js

Upvotes: 0

Related Questions