Render Props In React JS (part 2)
This is Second Part of an article, I will discuss about advance topic about renderProps
. The Topic is “ access therenderProps
component state
from invoked component and extend the view
of renderProps component from invoked component.
If you have no idea about renderProps
. you can read my first part of this article to know about basic understanding about render props,from below link.
Access the state
of other component or chield component from parent component by renderProps
.
In my previous article, I showed that, how to pass function as children
props into renderProps
component. By Render Props We can also access renderProps
component state
, only pass the state as argument to children
props from renderProps
component.
- First create
ResuableListView.jsx
file insrc
folder. it containsResuableListView
(renderProps) component.
(1) In line 6, set the selectedValue
state, which is then use for pass that value with children
props.
(2) In line 16…28, create the list view, from line 17 to 18, check the array has element by this.props.list && this.props.list(map => ...)
statement, in line 21 add the css style
which will create the cursor as pointer. in line 22, add the onclick function selectedItemValue
, which change the state of selectedValue
from list. In line 24, render the item
with text
value.
(3) Implement the function which will change the selectValue
state by using this.setState({})
function during selecting and unselecting element from list
.
(4) This is an special props
named children
for renderProps
, it will render the children
which is pass from invoked component as children
. children
also using for pass the value
to invoked component and extend the renderProps
component to invoked component.
Extend the renderProps
component to invoked component
In Figure 2, I have pass the book list as props to render
the list with ResuabledListView
.
From line 4 to 9, add BookList
array , which is then using it for render list in ReusableListView
. In line 15 to 22, I have implemented the ResuableListView
renderProps
element and extend the component to show the selected value to Books
component. In line 16 to 12 create the function and pass the function
as children
to ResuableListView
.
In line 17, check the ResuableListView
has selectedValue
which is pass from ResuableListView
component, show the selected value in div in Books.jsx (Invocked) component.
When user select the Item in ResuableListView
component, it will render the selectedValue
to Books.jsx
as part component, which is get from ResusableListView
.By following code, we can Extended the ResuableListView component from Books component without touching ResuableListView component.