Auto render custom html tags in ReactJs

57 Views Asked by At

In basic HTML, we are almost free to use any tag we want. I can write code like this:

<card>
  <header>
    <logo>
      <img src="..">
    </logo>
  <header>
  <subject>
  ..
  </subject>
  <information>
  ..
  </information>
<card>

I know it's not standard, but it's very organized!

Is there any creative way to make JSX support this syntax? I'm not talking about manually defining tags or components. I'm searching for a root solution to make React JSX support all custom tags automatically."

I tried:

const tags = ['card', 'header', 'logo', 'subject', 'information'];

const components = tags.reduce((obj, tag) => {
  obj[tag] = ({ children, ...props }) => React.createElement(tag, props, children);
  return obj;
}, {});

but it not work's and it not automatic

1

There are 1 best solutions below

0
On

You can create a function that dynamically generates React components based on a list of custom tags. Here's an example:

import React from 'react';

const CustomComponent = ({ tag, children, ...props }) => {
  const CustomTag = tag || 'div';
  return React.createElement(CustomTag, props, children);
};

const App = () => {
  const tags = ['card', 'header', 'logo', 'subject', 'information'];

  return (
    <CustomComponent tag="card">
      <CustomComponent tag="header">
        <CustomComponent tag="logo">
          <img src="..." alt="Logo" />
        </CustomComponent>
      </CustomComponent>
      <CustomComponent tag="subject">Subject content</CustomComponent>
      <CustomComponent tag="information">Information content</CustomComponent>
    </CustomComponent>
  );
};

export default App;