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;
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>
)
};
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>
);
}
}