Home > Blockchain >  Accessing nested elements's properties in React
Accessing nested elements's properties in React

Time:04-03

Imagine a situation where a certain component returns:

<Component1>
  <Component2 name="It's my name"/>
</Component1>

now, what I would like to achieve is something like this

<Component1 some_property={getComponent2'sName} //which evaluates to It's my name >
  <Component2 name="It's my name"/>
<Component1>

is this possible? If so, how?

For the context: both of these components are from (different) external packages, I'm not giving a specific example as the code is too messy in here and would only cause an unneeded headache.

CodePudding user response:

You can define a context, using React.createContext(), React.useContext and reducer, you can, you can see an example in this file: context sample

Where I defined 3 actions for the reducer, add to add a component to your set of components, remove to remove a component in a position and clean to clean your set. How can you use this context? First put the context in the code where you want to use it

<YourContextName>
  {Your react code}
</YourContextName>

How to call it? Use the hook useYourContextName() to define your state variables inside the parent component

const { yourContextNameState, setYourContextNameState } = useYourContextName();

Then you can use yourContextNameState to access to your component attributes

<Component1 some_property={yourContextNameState.components[0].Name}>
  <Component2 name={yourContextNameState.components[0].Name}></Component2>
</Component1>

Whenever you want to add a component use:

setYourContextNameState({type: "add", newComponent: {your object}});

Don't worry it's look like a big and hard code, but is super easy, just you can reused the code everywhere you want

CodePudding user response:

The simplest way to do this would be to store the string "It's my name" in a variable in the component that renders Components1 and Components2. Maybe something like this - ask if there is any confusion.

function ParentComponent() {
  const [name, setname] = useState("This is my name");

  return (
    <Component1 some_property={name}>
      <Component2 name={name}></Component2>
    </Component1>
  );
}
  • Related