I'm experimenting with React Hooks and I'm wondering how to target elements children with useRef. Actually, I know how to target an element with useRef. But I meet some problems when I'm trying to assign children to a variable.
Here's an example :
import React, { useState, useEffect, useRef } from "react";
import "./styles.css";
export default function App() {
let containerRef = useRef(null);
let title, subtitle;
const myEvent = () => {
console.log(title);
};
useEffect(() => {
title = containerRef.children[0];
subtitle = containerRef.children[1];
}, []);
return (
<div className="App" ref={el => (containerRef = el)}>
<h1 onClick={myEvent}>Hello World!</h1>
<h2>What's going on ?</h2>
</div>
);
}
I would like to access to the title and subtitle variables to create a function outside of useEffect. I know I'm wrong about the first declaration of title and subtitle. But actually I don't know how to fix this. I tried to use useState, but I failed to resolve my problem.
(Precisions : of course, in my real project, I just don't want display the variable in the console).
Can someone help me to fix this ?