Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to pass data to components without a parent?

I understand that the normal way is to pass props through a parent, but I want to know how else I can pass props to a component.

let C1 = createReactClass({

    ...
    render: function() {

        console.log('render C1');
        return (
            <div>
                <button onClick={this.cambiaAAzul}>Azul</button>
                <button onClick={this.cambiaAVerde}>Verde</button>
                <button onClick={this.cambiaARojo}>Rojo</button>
                <p>Estado C2 <strong style={ {color: this.state.color} }>{this.state.color}</strong></p>
                <C2 color={this.state.color}/> // It is common
            </div>
        );
    }
});

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Typically, to solve the props-drilling problem, which is what seems to be the issue you are trying to solve, the useContext hook should help.

So set up a context,

const C1ContextProvider = ({children}) => {

//...

// the Provider gives access to the context to its children
return (
  < C1Context.Provider value={someValue}>
    {children}
  </C1Context.Provider >
);

}

… and then in your component where you need someValue, you can just do this:

import React, { useContext } from "react";
import { C1Context } from "../C1Context";

//...
const values = useContext(AirDCPPSocketContext);
cons foo = values.someValue; // <-- someValue obtained from the context

//..

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading