Reputation: 21
I have 2 components A and B. How can pass a variable from component A to component B ?
ComponentA.js
const ComponentA = () => {
//INSET
const insets = useSafeAreaInsets();
//GET HEADER HEIGHT
const [heightHeader, setHeightHeader] = useState(false)
return (
<View
onLayout={({ nativeEvent }) => {
const { height } = nativeEvent.layout
setHeightHeader(height)
}}>
</View>
)
}
export default ComponentA
I want to get from
const [heightHeader, setHeightHeader] = useState(false)
the heightHeader variable
ComponentB.js
import ComponentA from './ComponentA';
const ComponentB = () => {
return (
<View style={{
flex:1
}}>
<View style={{
flex:1,
paddingTop: heightHeader,
}}>
</View>
</View>
)
}
export default ComponentB
I want to get heightHeader variable from ComponentA to ComponentB.
*The 2 Components isn't in the same file
Upvotes: 0
Views: 40
Reputation: 341
You need a Parent Component.
For Example in your app.js File you set the State heigthHeader. And in the return you pass the state as a Prop to your Components like this:
ComponentA:
const ComponentA = (props) => {
//INSET
const insets = useSafeAreaInsets();
//GET HEADER HEIGHT
return (
<View
onLayout={({ nativeEvent }) => {
const { height } = nativeEvent.layout
props.setHeightHeader(height)
}}>
</View>
)
export default ComponentA
}
ComponentB:
const ComponentB = (props) => {
return (
<View style={{
flex:1
}}>
<View style={{
flex:1,
paddingTop: props.heightHeader,
}}>
</View>
</View>
)
}
export default ComponentB
App.js:
const [heightHeader, setHeightHeader] = useState(props.heigthHeader)
...
return(<>
<ComponentA setHeightHeader=setHeightHeader/>
<ComponentB heightHeader=heightHeader/>
</>
...
Upvotes: 0