React/JSX how to specify a built-in HTML type as a variable

Viewed 166

I'm building a component that will use a native html type as its root element. For simplicity, let's say either a <td> or <th>. Doing this with user-defined components is easy since they are just functions that can be passed:

function MyWrapper(props) {
  const Element = props.element;
  <Element ...>
    ...
  </Element>
}

<MyWrapper element={MyComponent} />

But how can you pass a native html type, like <td> as element? I can get this to work if I define a silly wrapper function for each type I may want to pass in, e.g.:

const th = props => <th {...props} />;
<MyWrapper element={th} />

But I feel like I'm missing something about jsx by needing to define a function for a built-in component. Is there a another way to reference a dynamic but built-in component type without defining wrappers around a bunch of native html components?

1 Answers

Issue

You are trying to define what a th element is.

Solution

Pass the html element as a string.

<MyWrapper element={"th"} />

Demo

Edit react-jsx-how-to-specify-a-built-in-html-type-as-a-variable

function MyWrapper({ children, element: Element }) {
  return <Element>{children}</Element>;
}

const MyComponent = ({ children }) => <div>{children}</div>;

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>

      <MyWrapper element={MyComponent}>My Component</MyWrapper>
      <MyWrapper element={"th"}>Test</MyWrapper>
      <MyWrapper element={"td"}>Test</MyWrapper>
      <MyWrapper element={"li"}>Test</MyWrapper>
    </div>
  );
}

enter image description here

Related