Search code examples
reactjsreact-contextreact-class-based-component

How to use Context API in a class component


I'm working on a really big project with translations. I used Formspree to handle the forms. I want to translate that as well.

This is the code given by Formspree:

import React, { useContext } from "react";
import { LanguageContext } from "../../../../App";
import './Form.css';

export default class MyForm extends React.Component {
    constructor(props) {
        super(props);
        this.submitForm = this.submitForm.bind(this);
        this.state = {
            status: ""
        };
    }
    
    render() {
        const { status } = this.state;
        return (
            <form
                onSubmit={this.submitForm}
                action="https://formspree.io/f/********"
                method="POST"
            >
                {/* <!-- add your custom form HTML here --> */}
                <div className="container">
                    <label style={{ color: 'black', fontSize: '18px' }}>Name <span style={{ color: '#f14b4d' }}>(Required)</span>:</label>
                    <input type="text" name="Name" className='form-control mb-3' placeholder='Enter Your Name' required />
                    <label style={{ color: 'black', fontSize: '18px' }}>Email <span style={{ color: '#f14b4d' }}>(Required)</span>:</label>
                    <input type="email" name="Email" className='form-control mb-3' placeholder='Enter Your Email' required />
                    <label style={{ color: 'black', fontSize: '18px' }}>Message <span style={{ color: '#f14b4d' }}>(Required)</span>:</label>
                    <textarea type="text" name="Message" className='form-control mb-3' rows={3} placeholder='Tell Us Your Message' required />
                    <label style={{ color: 'black', fontSize: '18px' }}>Phone Number With Country Code <span style={{ color: '#6487FF' }}>(Optional)</span>:</label>
                    <input type="text" name="Phone" className='form-control mb-3' placeholder='Enter Your Phone Number' />
                    {status === "SUCCESS" ? <p className='mt-4' style={{ color: 'black' }}>Thanks For Your Message! Your Message Is Successfully Submitted!</p> : <button className='submit-contact-btn mt-3 mb-4'>Submit</button>}
                    {status === "ERROR" && <p style={{ color: 'black' }}>Oops! There was an error. Please Try Again</p>}
                </div>
            </form>
        );
    }

    submitForm(ev) {
        ev.preventDefault();
        const form = ev.target;
        const data = new FormData(form);
        const xhr = new XMLHttpRequest();
        xhr.open(form.method, form.action);
        xhr.setRequestHeader("Accept", "application/json");
        xhr.onreadystatechange = () => {
            if (xhr.readyState !== XMLHttpRequest.DONE) return;
            if (xhr.status === 200) {
                form.reset();
                this.setState({ status: "SUCCESS" });
            } else {
                this.setState({ status: "ERROR" });
            }
        };
        xhr.send(data);
    }
}

It's a mess for me because I don't work with class components I work with functional components.

I was trying to add my context in that file and it shows the exact same error every time.

Here's the error:

Error

I'm trying to put this code there:

const [isBangla, setIsBangla] = useContext(LanguageContext)

I tried putting this line of code many times but the error is same.


Solution

  • In your class component, you can define the contextType:

    static contextType = LanguageContext;
    

    Then you are able to use it via this.context, for example,

    this.context.setIsBangla()