const json = [
{
"type": "node",
"title": "Title 1",
"nodes": [
{
"type": "unit",
"name": "Unit01",
}
]
},
{
"type": "node",
"title": "Title 2",
"nodes": [
{
"type": "node",
"title": "Title 3",
"nodes": [
{
"type": "unit",
"name": "Unit10",
},
{
"type": "unit",
"name": "Unit11",
},
{
"type": "unit",
"name": "Unit12",
}
]
},
{
"type": "node",
"title": "Title 4",
"nodes": [
{
"type": "unit",
"name": "Unit20",
}
]
}
]
}
];
export default json;
import React, { Component} from 'react';
import json from './data'
class Node extends React.Component {
constructor(props) {
super(props);
this.state = {
showUnits: false,
}
this.onClickHandle = this.onClickHandle.bind(this);
}
onClickHandle(event) {
event.stopPropagation();
this.setState({showUnits: !this.state.showUnits});
}
render() {
const {showUnits} = this.state;
return (
<div className="node" onClick={this.onClickHandle}>{this.props.node.title}
<ul className="node__title" >
{showUnits && this.props.node.nodes.map(node => {
if (node.type === "node") {
return <Node node={node} value={this.props.value}/>
} else {
if (node.name.includes(this.props.value))
return <Unit unit={node} value={this.props.value}/>
}
})}</ul>
</div>
)
}
}
class Unit extends React.Component {
render() {
return (
<li className="unit__name">{this.props.unit.name}</li>
)
}
}
class SearchField extends React.Component {
constructor(props) {
super(props);
this.handleOnChange = this.handleOnChange.bind(this);
this.state = {
searchValue: "",
}
}
handleOnChange(event) {
const {value} = event.target;
this.setState({searchValue: value})
}
render() {
return (
<React.Fragment>
<form className="search-form">
<input type="text" className="search-form__input" placeholder="Поиск"
onChange={this.handleOnChange}/>
</form>
{json.map(node => <Node node={node} value={this.state.searchValue}/>)}
</React.Fragment>
)
}
}
class App extends Component {
render() {
return (
<main>
<SearchField/>
</main>
);
}
}
export default App;