I have a component that I am importing into a page:
function CodeVerify(props) {
const [value, setValue] = useState('');
const ref = useBlurOnFulfill({value, cellCount: CELL_COUNT});
const [propsCV, getCellOnLayoutHandler] = useClearByFocusCell({
value,
setValue,
});
return (
<SafeAreaView style={styles.root}>
<Text style={styles.title}>
Enter the code sent to your number
</Text>
<CodeField
ref={ref}
{...propsCV}
value={value}
onChangeText={setValue}
cellCount={CELL_COUNT}
rootStyle={styles.codeFiledRoot}
keyboardType="number-pad"
textContentType="oneTimeCode"
renderCell={({index, symbol, isFocused}) => (
<View
// Make sure that you pass onLayout={getCellOnLayoutHandler(index)} prop to root component of "Cell"
onLayout={getCellOnLayoutHandler(index)}
key={index}
style={[styles.cellRoot, isFocused && styles.focusCell]}>
<Text style={styles.cellText}>
{symbol || (isFocused ? <Cursor /> : null)}
</Text>
</View>
)}
/>
</SafeAreaView>
);
On the page, I render the component <CodeVerify />
How do I get the component's Value from the CodeVerify component?
CodePudding user response:
You can lifted up
your state from child
to parent
and then pass that data Here is the example:
Parent Component
import React, {useEffect, useState} from 'react';
import Child from "./Child";
function CParent(props) {
const [value, setValue] = useState(false);
function setOpeningValue(value) {
console.log('From Child to Parent:' value);
setValue(value);
}
return (
<div>
<Child setOpeningValue={setOpeningValue}/>
</div>
);
}
export default CParent;
Here we are passing
setOpeningValue
using the props likesetOpeningValue={setOpeningValue}
. From child component we are callingsetOpeningValue
with a value inparameter
so that we can received thatparameter
intoparent component
.
Child Component
import React, {useEffect, useState} from 'react';
// Child to Parent communication
function Child(props) {
const {setOpeningValue} = props;
const [value, setValue] = useState('');
function clickHandler() {
setOpeningValue(`changes is ${value}`);
}
function changeHandler(event) {
setValue(event.target.value);
}
return (
<div>
<input onChange={changeHandler} />
<button onClick={clickHandler}>pass data to parent</button>
</div>
);
}
export default Child;