M
M
Maksipes2019-07-18 13:21:11
React
Maksipes, 2019-07-18 13:21:11

Do they do this in Reacte?

Question about best practices in React.
There is an ItemsList component that loops the Item component. Each Item consists of several divs, several of which should respond to a click.
In order not to fence the garden from onClicks, I hang one onClick handler, lowered from the App component, on the root Item element, and I pass any click on the Item, the event itself and the index of the clicked Item to the top.

export default class Item extends React.Component {
  render() {
    const { item, index, onClick } = this.props;
    return (
      <div className="item" onClick={e => onClick(index, e)}>
        <div className="item-over">...</div>
        <div className="item-main">
          <div className="item-text">...</div>
          <div className="item-hint">...</div>
          <div className="item-extra">...</div>
        </div>
      </div>
    );
  }
}

In the App, where all the logic is, I accept:
onItemClick = (index, e) => {
    switch (e.target.className) {
      case "item-over":
        console.log("Клинкнут блок над айтмом " + index);
        break;
      case "item-text":
        console.log("Кликнут основной текст в айтеме " + index);
        break;
      case "item-hint":
        console.log("Кликнут доп текст в айтиме " + index);
        break;
      case "item-extra":
        console.log("Кликнут дополнительный блок а айтиме");
        break;
      default: {
      }
    }
  };

Well, before that, I naturally pass a link to the handler and the actual data to display:
<ItemsList items={items} onClick={this.onItemClick} />

The question is - is it normal to do this in React and if not - how to do it right?
In my opinion - a bunch of conditions in the handler does not look very good, and the identification of an element by class also looks somehow doubtful.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-07-18
@maksipes

It's not normal to do that. One of the goals pursued by the developers of modern frameworks is to avoid the need to manually check with DOM selectors.
Places like this are the source of a whole class of bugs when you forget that a selector is used in JS and rename or remove it. And they will find out that something has fallen off, perhaps only your users.
You can, of course, use additional selectors with prefixes: 'item__hint js--item__hint', but with the capabilities of modern frameworks, it is better and more convenient to refuse to check against DOM selectors and assign different listeners to different elements.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question