G
G
gsdev992019-03-22 17:55:46
JavaScript
gsdev99, 2019-03-22 17:55:46

How to correctly select ref (React)?

Hello. Guys, tell me, please, how to make a selection of ref.
How can I correctly select a collection instead of this:
const list = [...document.querySelectorAll('.list__item')];
The idea is that when next is clicked (for example) I need to add a class to the first list__item, for example, and also to the second one.

import React from "react";

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      items: [
        {id: 1},
        {id: 2},
        {id: 3},
        {id: 4},
        {id: 5},
        {id: 6},
        {id: 7},
        {id: 8},
        {id: 9},
        {id: 10}
      ]
    };
  }

  nextHandler = () => {

  };

  prevHandler = () => {

  };

  render() {
    return (
      <React.Fragment>
        <ul className="list">
          {
            this.state.items.map((item) => {
              return (
                <li
                  key={item.id}
                  className="list__item"
                >
                  <div className="list__item">
                    key={item.id}
                  </div>
                </li>
              );
            })
          }
        </ul>

        <div className="controls">
          <button type="button" onClick={this.prevHandler}>prev</button>
          <button type="button" onClick={this.nextHandler}>next</button>
        </div>
      </React.Fragment>
    );
  }
};

export default App;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-03-22
@gsdev99

Why do you need to ref each element of the list? Work with state. Most tasks in React development are solved without directly accessing DOM elements.
Remove this.init() from render and never do that. Read about component lifecycle .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question