pass multiple refs to child components

Viewed 2778

Before diving to the main problem, my use case is I am trying to handle the scroll to a desired section. I will have navigations on the left and list of form sections relative to those navigation on the right. The Navigation and Form Section are the child component. Here is how I have structured my code

Parent.js

const scrollToRef = ref => window.scrollTo(0, ref.current.offsetTop);

const Profile = () => {
  const socialRef = React.useRef(null);
  const smsRef = React.useRef(null);
  const handleScroll = ref => {
    console.log("scrollRef", ref);
    scrollToRef(ref);
  };
  return (
    <>
      <Wrapper>
        <Grid>
          <Row>
            <Col xs={12} md={3} sm={12}>
              <Navigation
                socialRef={socialRef}
                smsRef={smsRef}
                handleScroll={handleScroll}
              />
            </Col>
            <Col xs={12} md={9} sm={12}>
              <Form
                socialRef={socialRef}
                smsRef={smsRef}
              />
            </Col>
          </Row>
        </Grid>
      </Wrapper>
    </>
  );
};

Navigation.js(child component) I tried using forwardRef but seems like it only accepts one argument as ref though I have multiple refs.

const Navigation = React.forwardRef(({ handleScroll }, ref) => {
  // it only accepts on ref argument
  const items = [
    { id: 1, name: "Social connections", pointer: "social-connections", to: ref }, // socialRef
    { id: 2, name: "SMS preference", pointer: "sms", to: ref }, // smsRef
  ];
  return (
    <>
      <Box>
        <UL>
          {items.map(item => {
            return (
              <LI
                key={item.id}
                active={item.active}
                onClick={() => handleScroll(item.to)}
              >
                {item.name}
              </LI>
            );
          })}
        </UL>
      </Box>
    </>
  );
});

export default Navigation;

Form.js I do not have idea on passing multiple refs when using forwardRef so for form section I have passed the refs as simple props passing.

const Form = ({ socialRef, smsRef }) => {
  return (
    <>
      <Formik initialValues={initialValues()}>
        {({ handleSubmit }) => {
          return (
            <form onSubmit={handleSubmit}>
              <Social socialRef={socialRef} />
              <SMS smsRef={smsRef} />
            </form>
          );
        }}
      </Formik>
    </>
  );
};

Social.js

const Social = ({ socialRef }) => {
  return (
    <>
      <Row ref={socialRef}>
        <Col xs={12} md={3}>
          <Label>Social connections</Label>
        </Col>
        <Col xs={12} md={6}></Col>
      </Row>
    </>
  );
};

Can anyone help me at passing multiple refs so when clicked on the particular navigation item, it should scroll me to its respective component(section).

1 Answers

I have added an example below. I have not tested this. This is just the idea.

import React, { createContext, useState, useContext, useRef, useEffect } from 'react'

export const RefContext = createContext({});

export const RefContextProvider = ({ children }) => {
    const [refs, setRefs] = useState({});

    return <RefContext.Provider value={{ refs, setRefs }}>
        {children}
    </RefContext.Provider>;
};

const Profile = ({ children }) => {
    // ---------------- Here you can access refs set in the Navigation
    const { refs } = useContext(RefContext);
    console.log(refs.socialRef, refs.smsRef);

    return <>
        {children}
    </>;
};

const Navigation = () => {
    const socialRef = useRef(null);
    const smsRef = useRef(null);
    const { setRefs } = useContext(RefContext);

    // --------------- Here you add the refs to context
    useEffect(() => {
        if (socialRef && smsRef) {
            setRefs({ socialRef, smsRef });
        }
    }, [socialRef, smsRef, setRefs]);

    return <>
        <div ref={socialRef}></div>
        <div ref={smsRef}></div>
    </>
};


export const Example = () => {
    return (
        <RefContextProvider>
            <Profile>
                <Navigation />
            </Profile>
        </RefContextProvider>
    );
};

Related