Reputation: 2389
My goal is to render a child component without re-rendering it's parent component.
So for example, App's state is passed as a prop straight to the Column component but Column is a child of Table and Table has ShouldComponentUpdate
set to false (For example, table data didn't change..).
The problem.. if Apps state changes the Column component does not update.. unless ShouldComponentUpdate
is set to true
on the Table Component.. Is there anyway around this?
The documentation does say
Returning false does not prevent child components from re-rendering when their state changes.
But doesnt mention if their props change..
For test purposes I've created a demo here https://codesandbox.io/s/k2072rkp7o
Preview of the code:
const Column = ({ isSelected, onClick, children }) => (
<div
style={{
backgroundColor: isSelected ? 'green' : 'red',
padding: '10px',
}}
onClick={onClick}
>
Column: {children}
</div>
);
const Row = ({children }) => (
<div
style={{
backgroundColor: 'teal',
padding: '10px'
}}
>
Row {children}
</div>
)
class Table extends React.Component {
shouldComponentUpdate() {
// There will be logic here to compare table data to see if its changed..
return false
}
render() {
return (
<div
style={{
backgroundColor: '#ccc',
padding: '10px'
}}>
Table {this.props.children}
</div>
)
}
}
class App extends React.Component {
constructor() {
super();
this.state = {
isSelected: false
};
}
render() {
return (
<Table>
<Row>
<Column
isSelected={this.state.isSelected}
onClick={() => this.setState({
isSelected: !this.state.isSelected
})}
/>
</Row>
</Table>
)
}
}
Upvotes: 4
Views: 3250
Reputation: 2389
Ok, after more reading, it's not possible... Which isn't good when you are playing with tables and want to apply a style to a cell component without causing a re-render of the whole table... Will have to look into alternatives...
Heres the component lifecycle for anyone who has same problem..
Upvotes: 0
Reputation: 1064
U can use Table component to be PureComponent, and that PureComponent internaly checks for changes.
just change class Table extends React.Component
to class Table extends React.PureComponent
and then delete
shouldComponentUpdate() {
// There will be logic here to compare table data to see if its changed..
return false
}
because, as i said, PureComponent does that internaly. Read more at: PureComponent But don't use it always, because it can have side efect to slow your app down if used to much for unnecessary things.
Upvotes: 0
Reputation: 3228
Consider a solution where you are setting a default state onload and updating state where there is interaction with your table appending an 'color-whateveryoulike' class to your columns. Props won't help you in this instance because we never want to update props, you're wanting to listen for state updates.
Upvotes: 1