I'm pretty new to React and I was working on some JSON data. Now I just to understand basic concepts, so I wrote this little component, but in my eyes it's not efficient.
import React from 'react';
import {getJson} from './getJson';
import AddRow from './AddRow';
class TableComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
checked: true,
rows:[],
json: []
}
}
checkboxHandler() {}
componentDidMount() {
this.setState((prevState) => {
return {
json: getJson(),
}
})
}
checkAll = () => {
this.setState({
checked: !this.state.checked
})
this.setState(prevState => {
const json = prevState.json.map(obj => ({
...obj,
items: obj.items.map(item => ({
...item,
value: this.state.checked,
}))
}));
return { json };
});
};
render() {
return (
<div>
<table>
<tbody>
{this.state.json.map((obj, i) => {
return (
<tr key={obj.id}>
{obj.items.map((data, i) => {
return(
<td key={data.id}>
<p>{data.label}</p>
<input
type="checkbox"
checked={data.value}
onChange={this.checkboxHandler}
/>
</td>
)
})}
</tr>
)
})}
</tbody>
</table>
<button onClick={this.checkAll}>check\uncheck</button>
<AddRow actualJson={this.state.json}/>
</div>
)
}
}
export default TableComponent;
I'm not proud of it because I feel that I'm not respecting the heart of React - use module and components. Is there a way to have cleaner code?