So I have app.jsx which calls up all my other JSX files. This way I have each component organized in its own file. I would like to navigate to each section of the website (all on one page just different areas). The only issue is I can't seem to reference where I want to go to. I thought if I referenced the imported jsx file it would get its DOM elements. But that's not working. What seems to work is if I have a div directly being referenced in the same App.jsx file. But I need to get the child div element.
function App() {
const aboutmeOnClickRef = useRef(null);
const portfolioOnClickRef = useRef(null);
const employmentOnClickRef = useRef(null);
const educationOnClickRef = useRef(null);
const letschatOnClickRef = useRef(null);
return (
<div className="app">
<Topbar
aboutmeOnClickRef={aboutmeOnClickRef}
portfolioOnClickRef={portfolioOnClickRef}
employmentOnClickRef={employmentOnClickRef}
educationOnClickRef={educationOnClickRef}
letschatOnClickRef={letschatOnClickRef}
/>
<div className="sections">
<Intro />
<DisplayAboutMe ref={aboutmeOnClickRef} />
<Portfolio ref={portfolioOnClickRef} />
<Employment ref={employmentOnClickRef} />
<Education ref={educationOnClickRef} />
<LetsChat ref={letschatOnClickRef} />
</div>
</div>
);
}
//This is what I want to do, but doesn't work
//const DisplayAboutMe = React.forwardRef((props, ref) => <AboutMe ref={ref} />);
//This one works but creates a whole new div and doesn't get my jsx file
const DisplayAboutMe = React.forwardRef((props, ref) => <div ref={ref} />);
AboutMe.jsx
import React from "react";
import styles from "./aboutme.module.scss";
export default function AboutMe() {
return (
<div className={styles.aboutme} id={styles.aboutme}></div>
);
}
By default, refs to function components don't do anything. You need to use forwardRef to tell react which dom element you want the ref to point to. Currently, your about me component doesn't do this. Here's what it might look like:
import React from "react";
import styles from "./aboutme.module.scss";
const AboutMe = React.forwardRef((props, ref) => {
return (
<div ref={ref} className={styles.aboutme} id={styles.aboutme}></div>
);
});
export default AboutMe
With the above change, you shouldn't need DisplayAboutMe. App can render an <AboutMe>
and pass in a ref, and the ref will be assigned the div that's inside AboutMe.
function App() {
const aboutmeOnClickRef = useRef(null);
// ...
<div className="sections">
<Intro />
<AboutMe ref={aboutmeOnClickRef} />
</div>
// ...
}
// In topBar:
function TopBar(props) {
return (
// ...
<a onClick={() => { props.aboutMeOnClickRef.current.scrollIntoView() }}/>
// ...
)
}