I'm having trouble figuring out how to create a function that loads data (from a local json) into a li
element, and then adds a new component to the clicked li
upon click.
Here's an example of what I'm trying to achieve:
<ul>
<li> 1 </li>
<li> 2 </li>
<li>
3
<div id="data">
<!-- appended data -->
</div>
</li>
</ul>
When clicking on another li
, I want the previously added element to be removed and the new one to be added. Essentially creating a row toggle effect.
If anyone could point me in the right direction with React for this scenario, it would be much appreciated.
import React, { Component } from 'react';
import Flowers from 'flowers.json';
class Flowers extends React.Component {
constructor(props) {
super(props);
this.state = {
isToggleOn: true
};
this.onClick = this.handleClick.bind(this);
}
handleClick = (e) => {
console.log(this);
console.log(e);
console.log('li item clicked! ' + e.currentTarget);
// appends to clicked div
e.currentTarget.style.backgroundColor = '#ccc';
}
render() {
const List = Flowers.map((flower) =>
<li onClick={this.handleClick.bind(this)} key={flower.id} id={flower.id}>
{flower.name}
</li>
);
return(
<ul>{List}</ul>
);
}
}
class App extends Component {
render() {
return (
<Flowers />
);
}
}
export default App;