-1

I am using a class component in react and would like to know how I can add a CSS class to the current i.e clicked element which is inside a map statement. I would like to do it using state.

<div key={q.id} id={q.id}>
    <h2 className={this.state.title}>{q.title}</h2>
    <h3>{q.questionText}</h3>
    <div key={q.id}>
        {q.options.map((opt, index) => (
            <div
                key={opt.id}
                val={opt.val}
                ref={this.options}

                className={index === this.state.clickedItem ? 'myclass' : null}
                onClick={() => this.setState({ clickedItem: index })}>

                <p onClick={this.submitQuestion} ref={this.correctRef}>
                    {opt.text}
                </p>
            </div>
        ))}
</div>
ROOT
  • 11,363
  • 5
  • 30
  • 45
Donald
  • 31
  • 1
  • 5

2 Answers2

2

Here your state

state = {clickedItem: 0}

in render

yourArray.map((el, index) => {
  <div 
  onClick={() => this.setState({clickedItem: index})} 
  key={index} 
  className={index === this.state.clickedItem ? 'Your ClassName' : null}>
   {el.name}
  </div>
})
makkagru
  • 39
  • 1
0

In functional with useState hook, without class. Hope this can help.

https://codesandbox.io/s/blissful-boyd-6px43?file=/src/App.js

import "./styles.css";
/*
.is-checked {
  background-color: #901c1c;
  color: white;
}
*/


import React, { useState } from "react";

const App = () => {
  const tags = ["portrait", "événements", "voyage", "animaux"];
  const [clickedItem, setClickedItem] = useState(null);

  const handleCSS = (e) => {
    e.preventDefault();
    let selectedTag = e ? parseInt(e.target.id, 10) : null;
    setClickedItem(selectedTag);
    console.log(">> clickedItem", clickedItem);
  };

  return (
    <>
      <div className="App">
        <h1>Hello !</h1>
      </div>

      <div>
        {tags.map((tag, index) => {
          return (
            <button
              type="button"
              key={index}
              onClick={handleCSS}
              id={index}
              className={index === clickedItem ? "is-checked" : null}
            >
              {`#${tag}`}
            </button>
          );
        })}
      </div>
    </>
  );
};

export default App;
Nevada
  • 143
  • 1
  • 10