I have two components - <Parent/>
and <Book />
<Book />
is a (hopefully) re-usable component that I've written that manages its own state.
class Book extends React.component {
constructort(props) {
...
this.state = {page: 1}
}
nextPage() {
this.setState({page: this.state.page + 1})
}
prevPage() {
this.setState({page: this.state.page - 1})
}
render() {...}
}
The <Book />
component displays the correct page based on the page
property in its state. As you can see, there are 2 methods that can manipulate this state - imagine that these would get called when someone clicks on the next page
and previous page
buttons respectively
However, I do not want the "Next" and "Prev" buttons to be managed by the <book />
component. I want to give the developer who ends up using this component a way to invoke the nextPage()
and prevPage()
methods. This can happen when the user presses a button, when he/she swipes right - you get the idea.
The idiomatic way to manipulate a child's state is to pass it down as a prop from the parent. I cannot do it in this case because I do not want the parent to manage the state - I just want it to to be able to invoke some methods on the child that would, in turn, change the child's state.
In other words, the next developer does not want to think about what page the book should render. She just wants to let the book know that the page has to be turned. How do I achieve this abstraction in ReactJS?
EDIT: If it makes things any clearer, assume that the goal is to publish <Book />
as a re-usable library in npm.
EDIT: Is there a way to do it without using refs?