Reputation: 8942
I am using react-table and would like to render the table with/without subComponent based on a prop passed from the parent element.
I tried to update state -- new array with data
and columns
, but the table doesn't re-render.
js
import React from "react";
import { render } from "react-dom";
import { makeData, Logo, Tips } from "./Utils";
// Import React Table
import ReactTable from "react-table";
import "react-table/react-table.css";
const data = [
{
a: "32,000.02938488",
b: "0",
c: "32,000.02938488",
d: "55,000"
},
{
a: "32,000.02938488",
b: "0",
c: "32,000.02938488",
d: "55,000"
},
{
a: "32,000.02938488",
b: "0",
c: "32,000.02938488",
d: "55,000"
},
{
a: "32,000.02938488",
b: "0",
c: "32,000.02938488",
d: "55,000"
},
{
a: "32,000.02938488",
b: "0",
c: "32,000.02938488",
d: "55,000"
},
{
a: "32,000.02938488",
b: "0",
c: "32,000.02938488",
d: "55,000"
},
{
a: "32,000.02938488",
b: "0",
c: "32,000.02938488",
d: "55,000"
}
];
const columns = [
{
Header: "a",
accessor: "a"
},
{
Header: "b",
accessor: "b"
},
{
Header: "c",
accessor: "c"
},
{
Header: "d",
accessor: "d"
}
];
class Table extends React.Component {
state = {
columns: this.props.columns,
data: this.props.data
};
componentWillReceiveProps(nextProps) {
if (nextProps.expand !== this.props.expand) {
console.log("update data");
this.setState({
columns: [...nextProps.columns],
data: [...nextProps.data]
});
}
}
render() {
console.log(this.props.expand);
return (
<div>
{this.props.expand ? (
<ReactTable
data={this.state.data}
columns={this.state.columns}
showPagination={false}
defaultPageSize={data.length}
resizable={false}
SubComponent={row => {
return (
<div>
<h1>expanded state</h1>
</div>
);
}}
/>
) : (
<ReactTable
data={data}
columns={columns}
showPagination={false}
defaultPageSize={data.length}
resizable={false}
/>
)}
</div>
);
}
}
class App extends React.Component {
state = {
expand: true
};
componentDidMount() {
const that = this;
setTimeout(() => {
that.setState({ expand: false });
}, 2000);
}
render() {
const { expand } = this.state;
return (
<div>
<Table columns={columns} data={data} expand={expand} />
<br />
<Tips />
<Logo />
</div>
);
}
}
render(<App />, document.getElementById("root"));
Upvotes: 2
Views: 4733
Reputation: 39260
Looking in the source you should be able to reset the SubComponent, you con't do it with setting it to undefined though (something to do with how props would not overwrite state if it's undefined in props).
Setting SubComponent to null or false will get the desired results
class Table extends React.Component {
render() {
console.log("props:", this.props);
return (
<div>
<ReactTable
data={this.props.data}
columns={this.props.columns}
showPagination={false}
defaultPageSize={this.props.data.length}
resizable={false}
SubComponent={
this.props.expand
? row => (
<div>
<h1>expanded state</h1>
</div>
)
: false
}
/>
</div>
);
}
}
Upvotes: 1