Home > Back-end >  React add class to one element from list after clicking on button
React add class to one element from list after clicking on button

Time:12-13

I am rendering about 100 listItems like in code below. When I click on button, i want to show text only for that one element i have clicked on, but it shows text on everyone.

Another important thing is that i need this button only on phones

I know, there is another way using react state, but I need to use className.

Thank you all

const listItem = () => {
    let showMore = false;
    
            <div>
             <div className={`text ${showMore ? "active" : ""}`}>
              blablabla</div>
             </div>
              <button
                onClick={() => (showMore = !showMore)}>Show more</button>
}

<List>
 <listItem />
</List>

CodePudding user response:

In order to toggle className without using state, you can use ref. here is an example:

const ListItem = () => {
  const ref = React.createRef();
  return (
    <React.Fragment>
      <div>
        <div ref={ref} className={`text`}>
          blablabla
        </div>
      </div>
      <button
        onClick={() => ref.current.classList.toggle('active')}>
        Show more
      </button>
    </React.Fragment>
  );
};

function App(){
  return (
  <React.Fragment>
    <ListItem/>
    <ListItem/>
    <ListItem/>
  </React.Fragment>
  );
}

ReactDOM.render(<App/>, document.getElementById('root'))
.text{
  color: red;
  display: none;
}

.text.active{
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

CodePudding user response:

You should use useState in this case

Live Demo

Codesandbox Demo

const ListItem = ({ text }) => {
    let [showMore, setShowMore] = useState(false);

    return (
        <div className="item">
            <div>
                <div className={`text ${showMore ? "active" : ""}`}>{text}</div>
            </div>
            <button onClick={() => setShowMore((s) => !s)}>Show more</button>
        </div>
    );
};
  • Related