Render Props And Context In ReactJS

Introduction

 
In the previous article, we have learned about Higher-Order Components in React along with its usage. In this article, we will go through Render Props and the concept of Context in React.
 

Render Props

 
Render Props in React is something where a component’s prop is assigned a function and that is called in the render method of the component. Calling the function will return a React element or component. Third-party libraries like React Router and Downshift uses this approach.
 
A render prop is a function prop that the component uses to know what to render. Through this, we can also pass a state to another.
 
Let's see a demo.
 
Create a Movement.js file and code as below,
  1. import React, { Component } from 'react'  
  2.   
  3. export class Movement extends Component {  
  4.   
  5.     constructor(props) {  
  6.         super(props)  
  7.       
  8.         this.state = {  
  9.                 x:0,  
  10.                 y:0  
  11.         }  
  12.     }  
  13.       
  14.     onMouseMove =(event) => {  
  15.         this.setState({  
  16.             x:event.clientX,  
  17.             y:event.clientY  
  18.         })  
  19.     }  
  20.   
  21.     render() {  
  22.         const{x,y} = this.state  
  23.         return (  
  24.             <div style={{height : '100%'}} onMouseMove={this.onMouseMove}>  
  25.                 <h1> The current mouse position is ({x},{y})</h1>  
  26.             </div>  
  27.         )  
  28.     }  
  29. }  
  30.   
  31. export default Movement  
Now add this Movement.js in App.js,
  1. import React from 'react';  
  2. import './App.css';  
  3. import './css/custom.css';  
  4. import Movement from './components/Movement'  
  5.   
  6. function App() {  
  7.   return (      
  8.     <div>  
  9.       <Movement></Movement>  
  10.     </div>  
  11.   );  
  12. }  
  13.   
  14. export default App;  
The above code will display output as below.
 
Render Props And Context In ReactJS
 
Now let’s go further with the demo, we will create a component named Monkey in which on moving the mouse, the monkey will also move following the banana.
 
Let’s see the demo. Change the code of Movement.js as below.
  1. import React, { Component } from 'react'  
  2. import PropTypes from 'prop-types'  
  3.   
  4. export class Movement extends Component {  
  5.   
  6.     static propTypes = {  
  7.         render: PropTypes.func.isRequired  
  8.     }  
  9.   
  10.     state={x:0,y:0}    
  11.       
  12.     onMouseMove =(event) => {  
  13.         this.setState({  
  14.             x:event.clientX,  
  15.             y:event.clientY  
  16.         })  
  17.     }  
  18.   
  19.     render() {          
  20.         return (  
  21.             <div onMouseMove={this.onMouseMove}>  
  22.                {this.props.render(this.state)}  
  23.             </div>  
  24.         )  
  25.     }  
  26. }  
  27.   
  28. export default Movement  
Now, create Monkey.js with the below code. For below, we also need 2 images of monkey and banana respectively which are uploaded in the source code of Demo2.
  1. import React, { Component } from 'react'  
  2. import monkey from '../images/monkey.jpg'  
  3. import banana from '../images/banana.jpg'  
  4.   
  5. export class Monkey extends Component {  
  6.     render() {  
  7.         const{x,y} = this.props.Movement  
  8.   
  9.         return (  
  10.             <div>  
  11.                 <img src={monkey} alt='monkey' style={{position:'relative',left:x,right:y,height:150}}></img>                      
  12.                 <img src={banana} alt='banana' style={{position:'relative',left:(x+10),right:(y+10),height:30}}></img>                      
  13.             </div>  
  14.         )  
  15.     }  
  16. }  
  17.   
  18. export default Monkey  
Now, in the final step, call Monkey.js in App.js.
  1. import React from 'react';  
  2. import './App.css';  
  3. import './css/custom.css';  
  4. import Movement from './components/Movement'  
  5. import Monkey from './components/Monkey'  
  6.   
  7. function App() {  
  8.   return (      
  9.     <div>           
  10.       <Movement render={({x,y}) =>  (  
  11.         <Monkey Movement={{x,y}}/>  
  12.       )}/>  
  13.   
  14.     </div>  
  15.   );  
  16. }  
  17.   
  18. export default App;  
This will display the output as below.
 
In the above image, on moving the mouse, the monkey will also move. The above demo is quite interesting and lets us allow to animate other animation can be created using react-motion API.
 
Now, we will see the concept of Context in ReactJS.
 

Context

 
Context in React.js is the concept to pass data through a component tree without passing props down manually to each level.
 
In basic React application, to pass data from parent to child is done using props but this is a heavy approach if data needs to be passed on multiple levels like passing username or theme required by most of the components in the application. Context lets you provide the functionality to share values among components without explicitly passing props through every level of the component tree.
 
Mainly context is used when the current authentication, themes, or preferred language need to be passed to the child levels when not required to pass props.
 
To get data using context we need to follow 3 steps,
  1. We need to first create the context.
  2. Then we need to provide value to the context.
  3. Lastly, we need to consume the value of context.
Now let’s have a look at the demo,
 
For Example - In the current demo, we will see how to use username in child component using context. 
 
First, we will create a new file namely UserContext.js. This is the first step where we are creating context
  1. import React from 'react'  
  2.   
  3. const UserContext = React.createContext()  
  4.   
  5. const UserProvider = UserContext.Provider  
  6.   
  7. const UserConsumer = UserContext.Consumer  
  8.   
  9. export {UserProvider,UserConsumer}  
Now, we will create a nested structure in which I will create 3 level components Master Component -> Home Component -> Profile Component.
 
App.js in which we will execute second step we need to provide value to consumer,
  1. import React from 'react';  
  2. import './App.css';  
  3. import './css/custom.css';  
  4. import MasterComponent from './components/MasterComponent'  
  5. import { UserProvider } from './components/UserContext';  
  6.   
  7. function App() {  
  8.   return (  
  9.     <div className="App">  
  10.       <UserProvider value="New User">  
  11.         <MasterComponent />  
  12.       </UserProvider>  
  13.     </div>  
  14.   );  
  15. }  
  16.   
  17. export default App;  
MasterComponent.js 
  1. import React, { Component } from 'react'  
  2. import HomeComponent from './HomeComponent'  
  3. class MasterComponent extends Component {  
  4.     render() {  
  5.         return (  
  6.             <div>  
  7.                 <HomeComponent/>  
  8.             </div>  
  9.         )  
  10.     }  
  11. }  
  12.   
  13. export default MasterComponent  
Now second level component is named HomeComponent.js 
  1. import React, { Component } from 'react'  
  2. import ProfileComponent from './ProfileComponent'  
  3.   
  4. class HomeComponent extends Component {  
  5.     render() {  
  6.         return (  
  7.             <div>  
  8.                 <ProfileComponent/>  
  9.             </div>  
  10.         )  
  11.     }  
  12. }  
  13.   
  14. export default HomeComponent  
And third level Component named ProfileComponent in which we are going to consume context value
  1. import React, { Component } from 'react'  
  2. import { UserConsumer } from './UserContext';  
  3.   
  4. class ProfileComponent extends Component {  
  5.     render() {  
  6.         return (  
  7.            <UserConsumer>  
  8.                {  
  9.                    (username) => {  
  10.                        return <div>Hello {username}</div>  
  11.                    }  
  12.                }  
  13.            </UserConsumer>  
  14.         )  
  15.     }  
  16. }  
  17.   
  18. export default ProfileComponent  
Now the output will be displayed as below,
 
Render Props And Context In ReactJS
 
If in UserContext.js while creating context we will define default value and if in case we don't provide any value in component then it will take default value from UserContext,
  1. import React from 'react'      
  2. const UserContext = React.createContext('Guest')      
  3. const UserProvider = UserContext.Provider      
  4. const UserConsumer = UserContext.Consumer      
  5. export {UserProvider,UserConsumer}   
And App.js code will be as below,
  1. import React from 'react';  
  2. import './App.css';  
  3. import './css/custom.css';  
  4. import MasterComponent from './components/MasterComponent'  
  5. import { UserProvider } from './components/UserContext';  
  6.   
  7. function App() {  
  8.   return (  
  9.     <div className="App">  
  10.       {/* <UserProvider> */}  
  11.         <MasterComponent />  
  12.       {/* </UserProvider> */}  
  13.     </div>  
  14.   );  
  15. }  
  16.   
  17. export default App;  
The output will be as follows,
 
Render Props And Context In ReactJS
 
While using context we can only pass one value, for multiple values we need to use multiple context.
 
There is one more way to access context value using Context Type property.
 
First we need to export UserContext from UserContext.js file,
  1. import React from 'react'    
  2. const UserContext = React.createContext('Guest')      
  3. const UserProvider = UserContext.Provider      
  4. const UserConsumer = UserContext.Consumer      
  5. export {UserProvider,UserConsumer}    
  6. export default UserContext     
Now we will consume context value using contextType in HomeComponent.js
  1. import React, { Component } from 'react'  
  2. import ProfileComponent from './ProfileComponent'  
  3. import UserContext from './UserContext'  
  4.   
  5. class HomeComponent extends Component {  
  6.     render() {  
  7.         return (  
  8.             <div>  
  9.                 Home Component {this.contextType}  
  10.                 <ProfileComponent/>  
  11.             </div>  
  12.         )  
  13.     }  
  14. }  
  15.   
  16. HomeComponent.contextType = UserContext  
  17.   
  18. export default HomeComponent  
The output will be as below,
 
Render Props And Context In ReactJS
 
Accessing multiple context values,
  1. import React from 'react'      
  2. const UserContext = React.createContext('Guest')    
  3. const ThemeContext = React.createContext('theme')    
  4. const UserProvider = UserContext.Provider    
  5. const UserConsumer = UserContext.Consumer    
  6. const ThemeProvider = ThemeContext.Provider    
  7. const ThemeConsumer = ThemeContext.Consumer    
  8. export {UserProvider,UserConsumer,ThemeConsumer,ThemeProvider}    
  9. export default UserContext    
and using it in App.js,
  1. import React from 'react';  
  2. import './App.css';  
  3. import './css/custom.css';  
  4. import MasterComponent from './components/MasterComponent'  
  5. import { UserProvider,ThemeProvider } from './components/UserContext';  
  6.   
  7. function App() {  
  8.   return (  
  9.     <div className="App">  
  10.       <UserProvider value="New User">  
  11.         <ThemeProvider value="red">  
  12.         <MasterComponent />  
  13.         </ThemeProvider>  
  14.       </UserProvider>  
  15.     </div>  
  16.   );  
  17. }  
  18.   
  19. export default App;  

Now consuming value of ThemeProvider in ProfileComponent.js file,

  1. import React, { Component } from 'react'  
  2. import { UserConsumer,ThemeConsumer } from './UserContext';  
  3.   
  4. class ProfileComponent extends Component {  
  5.     render() {  
  6.         return (  
  7.            <UserConsumer>  
  8.                {  
  9.                    username => (  
  10.                     <ThemeConsumer>  
  11.                     {color => (  
  12.                          <div style={{ color: color }}>Hello {username}</div>  
  13.                     )}           
  14.                     </ThemeConsumer>         
  15.                )}  
  16.            </UserConsumer>  
  17.         )  
  18.     }  
  19. }  
  20.   
  21. export default ProfileComponent  
The output will be displayed as below,
 
Render Props And Context In ReactJS
 
Limitation of Context 
  1. Context can only be used with the class component.
  2. Using context type only a single context value can be accessed. For accessing multiple values, we will need to use nested consumer context.

Summary

 
In this article, we have learned about the concept of Render Props and Context and its usage in React. You can download source code attached along with this article. Now in the next article, we will learn about some advanced concepts of HTTP and how Get and Post methods are used in React to fetch data from Server.
 
Author
Priyanka Jain
0 9.6k 895.2k
Next » HTTP And React