I created a custom text pagination component(displaying the current pagination information. For example 1-N of total), and I found myself adding repeating code to the parent components(ComponentA and ComponentB). Every time I need to add the TextPagination component to the parent components, I need to add the same state and callback methods. If you look at ComponentA and ComponentB, they both have this.state = { itemCount: 0 } and the onDisplayLessData and onDisplayMoreData callback methods. This is something that I want to avoid, and especially, when other developers need to use the TextPagination component, they need to remember to add all of this...not so great in my opinion.
Component A
class ComponentA extends React.Component {
constuctor() {
super();
this.state = { itemCount: 0 }
}
render(){
// re-render data
<TextPagination .../>
}
onDisplayMoreData(){}
onDisplayLessData(){}
}
Component B
class ComponentB extends React.Component {
constuctor() {
super();
this.state = { itemCount: 0 }
}
render(){
// re-render data
<TextPagination .../>
}
onDisplayMoreData(){ //when child updates, this gets called }
onDisplayLessData(){ //when child updates, this gets called }
}
TextComponent
class TextPagination extends React.Component {
constructor() {
super();
this.state = { itemCount: 0, showLess: false };
this.displayMoreData = this.displayMoreData.bind(this);
this.displayLessData = this.displayLessData.bind(this);
}
render() {}
displayMoreData(value) {
// more code
// callback to notify the parent component
this.props.onDisplayMoreData(value);
}
displayLessData(value) {
// more code
// callback to notify the parent component
this.props.onDisplayLessData(value);
}
}
So, I figure to create another class called Pagination with this.state = { itemCount: 0 } and the callback methods, and have it extends to React.Component. Then ComponentA and ComponentB can extend from Pagination class.
Example:
class Pagination extends React.Component {
constructor() {
super();
this.state = {
itemCount: 0
};
this.onDisplayMoreData = this.onDisplayMoreData.bind(this);
this.onDisplayLessData = this.onDisplayLessData.bind(this);
}
onDisplayMoreData(itemCount) {
this.setState({
itemCount: itemCount
});
}
onDisplayLessData(itemCount) {
this.setState({
itemCount: itemCount
});
}
}
ComponentA extends Pagination {
constructor() { super(); }
render() {
// re-render data
<TextPagination .../>
}
}
ComponentB extends Pagination {
constructor() { super(); }
render() {
// re-render data
<TextPagination .../>
}
}
This approach seems to work without any problems. ComponentA and ComponentB no longer have to have the state and callback methods.Other developers do not need to remember to add the state and callback methods when using TextPagination.
Is this the right solution? If not, please give me some advice.
Darn it, it just occurred to me if ComponentA or ComponentB needs to add additional state, then it will overwrite the original parent's state...is that correct?
Thanks for your help!