LeeM
LeeM

Reputation: 25

Pass props 'as' and render tag html in React

I want to pass in a component props named as.

As will be bound to html tags and "link" string .

If it's a link I want it to return the Link component of react-router-dom

In the remaining cases, whatever name tag is passed, it will be rendered.

For example :

as="div" -> render <div></div>

as="span" -> render <span></span>

as="link" -> render <Link></Link>

Can you help me

Upvotes: 1

Views: 37

Answers (1)

Konrad
Konrad

Reputation: 24651

const Component = ({ as, children }) => {
  if (as === "link") return <Link>{children}</Link>;
  const Comp = as;
  return <Comp>{children}</Comp>;
};

Working example:

Edit stoic-poincare-58ck6l

Upvotes: 1

Related Questions