0

i want to get context of base_url, based on https://reactjs.org/docs/context.html but it show error. even directly using this.context still gives same error, the codes works if im using direct function instead class. im using reactjs inside vite laravel 9 (even not using vite, directly use reactjs still gives same error)

import './bootstrap';
import React from 'react';
import ReactDOM from 'react-dom/client';

const root = ReactDOM.createRoot(document.getElementById('dashboard'));
const dashboardDivTag = document.getElementById('dashboard');
const GlobalParamContext = React.createContext({
    base_url : dashboardDivTag.getAttribute('baseUrl')
});

/*******************************/

class SideMenuButton extends React.Component {
    constructor(props) {
        super(props);
        // This binding is necessary to make `this` work in the callback
        this.SideMenuClicked = this.SideMenuClicked.bind(this);
    }
    SideMenuClicked() {
        let test = this.context; //Cannot read properties of undefined (reading 'context')
        console.log(test); 
    }
    
    render() {
        return (
            <div onClick={this.SideMenuClicked}></div>  
        );
    }
}
SideMenuButton.contextType = GlobalParamContext;

class TopBar extends React.Component {
    render() {
        return (
        <div class="bg-slate-900 h-11">
            <SideMenuButton />
        </div>
        );
    }
}

/*******************************/

//this is not work, still undefined
//root.render(
//  <TopBar />
//);

//this is not work too, still undefined
root.render(
    <GlobalParamContext.Provider>
    <TopBar />
    </GlobalParamContext.Provider>
);

this is console.log(this) result : enter image description here

Lezir Opav
  • 674
  • 3
  • 6
  • 21

0 Answers0