2

I'd like to create a <Breadcrumb> component which receives a <Link> component as a dependency.

This could be a <Link> component from react-router-dom or an <a> component.

How can I get direct access to the <a> component so that I may inject it into <Breadcrumb>?


Here is a brief example of what I'm trying to do.

const createBreadcrumbComponent = (Link) => {
    return function Breadcrumb(props) {
        // return JSX that renders this Link component 
        // A basic example:
        return <Link href="/">{"Home"}</Link>
    }
}

An example of using this with react-router-doms own <Link component:

// import {Link} from 'react-router-dom';
const Breadcrumb = createBreadcrumbComponent(Link);

I would like do the same as above, but substitute Link with a. Unfortunately there doesn't seem to be an actual component that represents a (with React.createElement() we pass the string "a" instead).

1
  • 1
    Can you provide a code example of what you've tried so far? Commented Oct 22, 2020 at 19:57

2 Answers 2

3

You can always use ref to access the underlying DOM element from a React Component. But, this is not always the case.

Following are the cases, which will enable you to use ref -

  1. The component is a native HTML element, for eg - a, div, img etc.
  2. The React native component is wrapped with a forwardRef. This doc explains it nicely - https://reactjs.org/docs/forwarding-refs.html

An example for using ref can be seen below -

import React, {useRef} from 'react';

const Comp = () => {
  const elRef = useRef();

  useEffect(() => {
    console.log(elRef.current); // -> the p element
  }, []);

  return <p ref={elRef}>Hello</p>;
}

There is a third way of getting the underlying element, but I don't recommend it since it is deprecated. You can use ReactDOM.findDOMNode(Component). This is a part of react-dom package. You can read more about it here - https://reactjs.org/docs/react-dom.html#finddomnode

Sign up to request clarification or add additional context in comments.

Comments

0

I think the solution is to create a wrapper around <a>, for instance:

const A = (props) => <a {...props}/>;
const Breadcrumb = createBreadcrumbComponent(A);

I was hoping there would be a way to obtain a component directly from React that already encompasses the <a> element

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.