Just a learner
Just a learner

Reputation: 28552

React passing data from parent to child component using context doesn't work

I'm very new to React and I did some experiment to learn the context object. My aim is to pass a background color from parent component to the deepest nested child component. Below is my code.

import React, {Component} from "react";
import ReactDOM from "react-dom";
import "./index.css";


let {Provider, Consumer} = React.createContext();

class Parent extends Component {
    render() {
        return (
            <Provider value={this.state.color}><Level1Child></Level1Child></Provider>
        );
    }

    constructor(props) {
        super(props);
        this.state = {
            color: "bg-indigo-300"
        };
    }
}


class Level1Child extends Component {
    render() {
        return (
            <Level2Child></Level2Child>
        );
    }
}


class Level2Child extends Component {
    render() {
        return (
            <Level3Child></Level3Child>
        );
    }
}


class Level3Child extends Component {
    render() {
        return (
            <div className={<Consumer>{(stuff) => stuff}</Consumer>}>Data</div>
        );
    }
}


ReactDOM.render(
    <Parent />,

    document.getElementById("root")
);

When I run it, the generated child component looks like this.

<div id="root"><div class="[object Object]">Data</div></div>

The color class was not passed. How can I make it work? Thanks.

Upvotes: 0

Views: 203

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 84902

class Level3Child extends Component {
    render() {
        return (
            <div className={<Consumer>{(stuff) => stuff}</Consumer>}>Data</div>
        );
    }
}

You need to flip this around. The context consumer needs to be on the outside, and the div on the inside.

class Level3Child extends Component {
  render() {
    return (
      <Consumer>
        {(stuff) => (
          <div className={stuff}>Data</div>
        )}
      </Consumer>
    )
  }
}

Upvotes: 1

Related Questions