Shane Callanan
Shane Callanan

Reputation: 521

How to get access to the underlying component of a react html element?

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).

Upvotes: 2

Views: 2037

Answers (2)

Rudraprasad Das
Rudraprasad Das

Reputation: 368

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

Upvotes: 2

Shane Callanan
Shane Callanan

Reputation: 521

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

Upvotes: 0

Related Questions