Home > Software engineering >  How can i return an html in a function in javascript as in jsx (react)?
How can i return an html in a function in javascript as in jsx (react)?

Time:01-20

I want to create a function and have it return an html like in react (Without use react or jsx)

const func = () => {
  return (
    <h1>Hello World!</h1>
  );
}

CodePudding user response:

Without use react or jsx

If you don't want to use JSX then clearly you can't use JSX. You can return a string:

const func = () => {
  return '<h1>Hello World!</h1>';
}

document.querySelector('#test').innerHTML = func();
<div id="test"></div>

Or perhaps an element:

const func = () => {
  const el = document.createElement('h1');
  el.innerText = 'Hello World!';
  return el;
}

document.querySelector('#test').appendChild(func());
<div id="test"></div>

CodePudding user response:

Here's a solution

function createHTML(element, props, children) {
  const startTag = `<${element}`;
  const endTag = `</${element}>`;

  let htmlString = startTag;

  for (let prop in props) {
    htmlString  = ` ${prop}="${props[prop]}"`;
  }

  htmlString  = '>';

  if (children && Array.isArray(children)) {
    for (let i = 0; i < children.length; i  ) {
      htmlString  = children[i];
    }
  } else if (children && typeof children === 'string') {
    htmlString  = children;
  }

  return htmlString   endTag;
}
  • Related