Skip to main content

Command Palette

Search for a command to run...

Using Context API in React ( Classes)

Updated
2 min readView as Markdown
Using Context API in React ( Classes)
static contextType = UsersContext;

here , we can use only one by writing this With that you're telling React hey this component should have access to the user's context context, but you can only set the static context type property once so if there are two contexts which should be connected to one at the same component, this would simply not be an option, you would have to find some other work around like wrapping it in a number component or anything like that.

users-context.js

import React from 'react';

const UsersContext = React.createContext({
  users: []
});

export default UsersContext;

App.js

import UserFinder from './components/UserFinder';
import UsersContext from './store/users-context';

const DUMMY_USERS = [
  { id: 'u1', name: 'Max' },
  { id: 'u2', name: 'Manuel' },
  { id: 'u3', name: 'Julie' },
];

function App() {


  const usersContext = {
    users: DUMMY_USERS
  }


  return (
    // value={{users:[{},{},{}]}}
    <UsersContext.Provider value={usersContext}>
      <UserFinder />
    </UsersContext.Provider>
  );
}

export default App;

the context consumer component can be used in both functional and class based component

UserFinder.js

import { Fragment, Component } from 'react';
import classes from './UserFinder.module.css'
import Users from './Users';
import UsersContext from '../store/users-context';

class UserFinder extends Component {


static contextType = UsersContext;

    constructor(props) {
        super(props);
        this.state = {
            filteredUsers: [],
            searchTerm: ''
        }

    }

;


    componentDidMount(){
    this.setState({filteredUsers:this.context.users});
    // console.log(this.context)
    }


    componentDidUpdate(prevProps, prevState) {
        if (prevState.searchTerm !== this.state.searchTerm) {      
            this.setState({
                filteredUsers: this.context.users.filter((user) =>
                    user.name.includes(this.state.searchTerm)
                ),
            });
        }
}



    render() {
        return (
            <Fragment>
                <div className={classes.finder}>
                    <input type='search' onChange={this.searchChangeHandler.bind(this)} />
                </div>
                <Users users={this.state.filteredUsers} />
            </Fragment>
        );
    }
}

export default UserFinder;

More from this blog

Omar's blog

135 posts