comewithme38
@comewithme38

Как вывести div с конкретным элементом при клике на него в react?

Я вывожу элементы массива в виде списка. Сейчас при клике на элемент, он добавляется вниз списка. Но я хочу вывести(отрендерить) рядом отдельный div с этим элементом.

import React, {Component} from 'react';


class List extends Component {
    render() {
        return (
            <div>
                {this.props.items.map((item, index) =>
                    <li key={index} onClick={() => this.props.addToArray(item.id)}>{item.id}</li>
                )}
            </div>
        );
    }
}

class App extends Component {
    state = {
        menu: [
            {
                link: 'link1',
                id: 'Articles'
            },
            {
                link: 'link2',
                id: 'Contacts'
            },
            {
                link: 'link3',
                id: 'Posts'
            },
            {
                link: 'link1',
                id: 'Lorem'
            },
            {
                link: 'link2',
                id: 'Ipsum'
            },
            {
                link: 'link3',
                id: 'Test'
            }
        ]
    }

    addToArray = (id) => {
        this.setState(state => {
            return {
                menu: [...state.menu, {id, link: 'link'}]
            }
        })
    }

    render() {
        return (
            <div>
                <List items={this.state.menu} addToArray={this.addToArray}/>
            </div>
        );
    }
}

export default App;
  • Вопрос задан
  • 714 просмотров
Решения вопроса 1
0xD34F
@0xD34F Куратор тега React
Так может быть показан блок с дополнительным контентом только у одного элемента списка:

const List = ({ items }) => {
  const [ active, setActive ] = React.useState(null);

  function onClick(e) {
    const index = +e.target.dataset.index;
    setActive(active === index ? null : index);
  }

  return (
    <ul>
      {items.map((n, i) => (
        <li key={n.id}>
          <span data-index={i} onClick={onClick}>{n.id}</span>
          {active === i ? <div>{n.link}</div> : null}
        </li>
      ))}
    </ul>
  )
};

А так - у нескольких одновременно:

const List = ({ items }) => {
  const [ active, setActive ] = React.useState({});

  const onClick = ({ target: { dataset: { index } } }) =>
    setActive(active => ({ ...active, [index]: !active[index] }));

  return (
    <ul>
      {items.map((n, i) => (
        <li key={n.id}>
          <span data-index={i} onClick={onClick}>{n.id}</span>
          {active[i] ? <div>{n.link}</div> : null}
        </li>
      ))}
    </ul>
  )
};
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 1
comewithme38
@comewithme38 Автор вопроса
class List extends Component {
  render() {
    const {activeElement, items, setActiveElement} = this.props;
    return (
      <div style={{display: 'flex'}}>
        <div style={{marginRight: 50}}>
          {items.map((item, index) => (
            <li key={index} onClick={() => setActiveElement(item)}>
              {item.id}
            </li>
          ))}
        </div>
        {activeElement ? (
          <div>
            <h2>{activeElement.id}</h2>
          </div>
        ) : null}
      </div>
    );
  }
}

class App extends Component {
  state = {
    activeElement: null,
    menu: [
      {
        link: "link1",
        id: "Articles"
      },
      {
        link: "link2",
        id: "Contacts"
      },
      {
        link: "link3",
        id: "Posts"
      },
      {
        link: "link1",
        id: "Lorem"
      },
      {
        link: "link2",
        id: "Ipsum"
      },
      {
        link: "link3",
        id: "Test"
      }
    ]
  };

  setActiveElement = (item) => {
    this.setState({
      activeElement: item
    })
  }

  render() {
    return (
      <div>
        <List 
          items={this.state.menu}
          activeElement={this.state.activeElement} 
          setActiveElement={this.setActiveElement} 
        />
      </div>
    );
  }
}
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы