Good day everyone, I am having issues passing an innerText value to a parent component
Below is a screenshot for the parent component and the child component
Parent Component which I want to receive the innerText value
<input type="text"
value={value}
className='display_text'
ref={outputRef}
readOnly
/>
<div className="flex">
<PaperLetter sd={setValue}>teeth.</PaperLetter>
<PaperLetter>brush</PaperLetter>
<PaperLetter>my</PaperLetter>
<PaperLetter>i</PaperLetter>
</div>
Child Component which I want to send the innerText value from
export default function PaperLetter(props) {
const [clicked, setclicked] = useState(false);
const letterRef = useRef();
const btnClicked =()=>{
//Change the className of the btn clicked to active
setclicked(true);
//Get the value of the letter btns clicked
const getValue = letterRef.current.innerText;
// How to pass this value to my parent component inorder to
update a state in the parent component is the major chanllege
}
return (
<p className={clicked ? 'letter clicked': 'letter'}
onClick={btnClicked} ref={letterRef} >{props.children}
</p>
)
}
state I want to update after receiving the value
const [value, setValue] = useState('i brush')
Screenshoots are also available via the link for proper view
CodePudding user response:
Parent:
const [text, setText] = useState('');
const handleInnerText = (innerText) => {
setText(innerText);
}
<input type="text"
value={value}
className='display_text'
ref={outputRef}
readOnly
/>
<div className="flex">
<PaperLetter handleInnerText={handleInnerText} sd={setValue}>teeth.</PaperLetter>
<PaperLetter>brush</PaperLetter>
<PaperLetter>my</PaperLetter>
<PaperLetter>i</PaperLetter>
</div>
Child:
export default function PaperLetter(props) {
const [clicked, setclicked] = useState(false);
const letterRef = useRef();
const btnClicked =()=>{
//Change the className of the btn clicked to active
setclicked(true);
//Get the value of the letter btns clicked
const getValue = letterRef.current.innerText;
// How to pass this value to my parent component inorder to
update a state in the parent component is the major chanllege
props.handleInnerText(getValue);
}
return (
<p className={clicked ? 'letter clicked': 'letter'}
onClick={btnClicked} ref={letterRef} >{props.children}
</p>
)
}
Now innerText will be saved in your parent comp variable as : text
