综合技术

React’s New Context API With Example

微信扫一扫,分享到朋友圈

React’s New Context API With Example
0

This tutorial help to understand React Context API With Example.The react provides Context API to pass parameters and data across the component without props.

The new context API introduced with version 16.3. The React Context API’s are very useful in state management without props drilling in components.This is same as global variable in other languages.

The react normally pass data from one component to other using top-down (parent to child) via props, but this process is tedious if the some data needed through across react components like, current authenticated user, theme, locale information.You can use props if the data required by some components within the application.

Table of Contents

Simple React Context API With Example

Lets’ create react project to understand working functionality of context api. Open the command line and run below command –

npx create-react-app context-api-example

cd context-api-example

start the react application –

npm start

Create React Context API Object

Let’s create context-api
object into app.js
file.The React.createContext()
method is use to create object and returns the Context object.

import { createContext } from 'react';
const {Provider, Consumer } = React.createContext();

Now, We will create the wrapper component that will return the Provider component.We will add as a children all the elements from which you want to access the context.The below code will add into app.js
file –

class ProviderComponent extends Component {
    state = {
        username : "adam",
    }
render() {
        return ( 
        <Provider value={this.state}>
          <Navbar />
        </Provider>
        )
    }
}

Lert’s create Navbar componennet,

const Navbar = () => (
  <div>
    <LoggedInContainer>
  </div>
)

Now we will access username data from provider component to Navbar
component. We are accessing state of provider component using context API.

const LoggedInContainer = () => (
  <div>
     <a href="#" class="dropdown-toggle" data-toggle="dropdown">Welcome, {(context) => context.username} <b class="caret"></b></a>
  </div>
)

Conclusion

We have created simple react application, that is simply consume state of provider component using context without prop drilling.Its help to create global variable that required by many components within the application.You can use redux
as well for complex application.

阅读原文...


微信扫一扫,分享到朋友圈

React’s New Context API With Example
0

Avatar

快速定位NodeJs线上问题 - 之火焰图篇

上一篇

『助力智慧检务』 世平信息荣获“2019全国政法智能化建设优秀解决方案供应商”

下一篇

评论已经被关闭。

插入图片

热门分类

往期推荐

React’s New Context API With Example

长按储存图像,分享给朋友