'React: How to pass a pointer to one component to a second component
How can you pass a pointer to component 1 to component 2 (so that you can work with component 1 inside component 2, e.g. get its properties)
<Component1 />
<Component2 target = {Component1} />
In part, this problem can be solved by handling events from component 1, because in this case a зpointer to it (event.target) will be available, but what about before such an event occurs?
Solution 1:[1]
Instead of passing throw props just import your component 1 in component2 if you want to use content of component1 in component2 and your good to go ?
Or if you what to use component2 as wrapper you can use children props
For example:
function Component2(props) {
return (
<div className={'component2'}>
{props.children}
</div>
);
}
export default Component2
and use it
import Component2 from './component2'
import Component1 from './component1'
function App() {
return (
<Component2>
<Component1/>
</Component2>
);
}
export default App
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | marc_s |