skip to Main Content

I am trying to build a UI for a website builder where the user can can create components and add them to a website. Once the options are selected, I am having trouble creating the element with my js function to render it onto my react page.

Please See My code below



const Page = () => {

  componentList = [{
    details: {
      content: 'Example Title',
      fontSize: 'large',
      fontType: 'Rubik',
      color: '#e67e22'
    },
    type: 'heading'
  }]

  const createHtmlElements = (component: Component) => {
    if (component.type === "heading") {
      let heading = document.createElement("h2");
      heading.innerHTML = component.details.content;
      return heading;
    }
  };


  

  const renderComponents = componentList.map((component) => {
    return createHtmlElements(component);
  });

  console.log(renderComponents);

  return (
    <>
      {renderComponents}

    </>
  );
};

export default Page;

What exactly would I need to do here to render onto my react page an HTML heading with the content displayed inside of it?

Any help would be greatly appreciated, thanks

P.S Next step will be styling the built component using the attributes so any tips on that wwould be greatly appreciated as well

Thanks,

3

Answers


  1. Replace return statement with the below code :

     return <renderComponents />;
    
    

    Reason: Here renderComponent is React component, not a variable as per React rules, Hence you cannot treat it as a variable.

    Login or Signup to reply.
  2. The error means that your react element is getting object instead of html .The code seems correct just your return statement.

    return (
        <>
          {renderComponents()}
    
        </>
      );
    
    Login or Signup to reply.
  3. Better not to mix content and style together. Just closely look how the componentList[] should look like. Also the type should directly annotate the actual html element. If you still returns it as ‘header’, then control if from the code(in createHtmlElements).

    function App() {
      let componentList = [{
        details: {
          content: 'Example Title',
          style: {
            fontSize: 'large',
            fontType: 'Rubik',
            color: '#e67e22',
          }
        },
        type: 'h2',
      }]
    
      const createHtmlElements = (component) => {
        const { details: { content, style }, type } = component;
    
        return React.createElement(
          type,
          { style },
          content
        );
      };
    
    
      const renderComponents = componentList.map((component) => {
        return createHtmlElements(component);
      });
    
    
      return (
        <>
          {renderComponents}
        </>
      );
    }
    

    ps: Refer to createElement api to understand how you can easily create React elements.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search