1

I am using our cartContext in a functional component like this:

import { CartContext } from '../../contexts/CartContext';

function staticCart(){
    const { increase, decrease, removeProduct } = useContext(CartContext);
    const { total, cartItems, shipping, netTotal, vat, finalTotal } = useContext(CartContext);
    return (
         <React.Fragment>Logic to use the complex cart contexts</React.Fragment>
    )
}

And this working fine as expected. And we have a class-based component, which looks like this:

import- statements

class StaticCart extends COmponent<RouteComponentProps<any>, State> {
    protected datatypes
    
    constructor(props: any) {
        ...
    }
    componentDidMount() {
        ...
    }

    render() {
        return (
            <React.Fragment>
                ...
            </React.Fragment>
        )
    }
}

I am trying to add the above same method(as in functional components) to the class Components.

I have tried:

2 Answers 2

2

Creating a context in React will give 2 things one is the Provider and Consumer . The Provider remains the same for both the class and functional components.

For functional components we can replace the Consumer with the useContext. But for class components you need to use Consumer

<CartContext.Consumer>
{(value) => { return ( .... )}}
</CartContext.Consumer>
Sign up to request clarification or add additional context in comments.

Comments

0

I ended up using this approach,

import- statements

class StaticCart extends COmponent<RouteComponentProps<any>, State> {
    protected datatypes
    
    static contextType = CartCOntext;
    constructor(props: any) {
        ...
    }
    componentDidMount() {
        ...
    }

    render() {
        const { increase, decrease, removeProduct } = useContext(CartContext);
const { total, cartItems, shipping, netTotal, vat, finalTotal } = useContext(CartContext);
        return (
            <React.Fragment>
                ...
            </React.Fragment>
        )
    }
}

Which has worked for me.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.