'How to in React Component constructor set this state
I still learn much React JavaScript and now I can't understand how to create this initial state.
In the constructor here in the code I want to add to state by running this line:
this.state = CsvViewer.parse(props.data);
And direct after I want to add more state variables like this:
this.state = {
filters: {},
sortColumn: null,
sortDirection: null,
};
The problem now is that state does not contain the first call to CsvViewer. How can I add to state both the call to CsvViewer and the other state variables?
Code:
class CsvViewer extends Component {
static parse(data) {
const rows = [];
const columns = [];
new CSV(data).forEach(array => {
if (columns.length < 1) {
array.forEach((cell, idx) => {
columns.push({
key: `key-${idx}`,
name: cell,
resizable: true,
sortable: true,
filterable: true,
});
});
} else {
const row = {};
array.forEach((cell, idx) => {
row[`key-${idx}`] = cell;
});
rows.push(row);
}
});
return { rows, columns };
}
constructor(props) {
super();
this.state = CsvViewer.parse(props.data);
this.state = {
filters: {},
sortColumn: null,
sortDirection: null,
};
}
UNSAFE_componentWillReceiveProps(nextProps) {
// TODO
this.setState(CsvViewer.parse(nextProps.data));
}
handleGridSort = (sortColumn, sortDirection) => {
// this.setState({ sortColumn, sortDirection });
};
render() {
const { rows, columns } = this.state;
const { height } = this.props;
return (
<ReactDataGrid
enableCellAutoFocus={false}
columns={columns}
rowsCount={rows ? rows.length: 0}
rowGetter={i => rows[i]}
minHeight={height || 650}
onGridSort={this.handleGridSort}
/>
);
}
}
export default CsvViewer;
Solution 1:[1]
You can set csvViewer, filters, sortColumn, and sortDirection under one state like so.
constructor(props) {
super();
this.state = {
csvViewer: CsvViewer.parse(props.data),
filters: {},
sortColumn: null,
sortDirection: null,
};
}
The second this.state will overwrite your first this.state, you can have everything under one state.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dparr |
