skip to Main Content

I have an unusual requirement. My site is build with React and I want people to be able to copy the public website’s HTML into their own React components.

The only issue that I’m having is inputs do not have a closing tag when rendered by React.

Both of these are valid HTML

<input id="input-1" value="foo">
<input id="input-2" value="foo" />

However only the 2nd one will work if pasted directly into a React component. Is there a way to force React to render the closing tag for inputs on my site?

2

Answers


  1. To understand this correctly, users can post the HTML into your app, and it needs to be rendered as JSX? And the issue you’re facing is that users can add non self-closing HTML input tags, but that’ll be an issue when rendering JSX (as they need to be self closing)?

    You could perform a check to see if the tag being entered is an input, and if it isn’t self-closing, and then close it yourself. That would look something like this (assuming you have the field in some var):

    if(var.substring(1,6) == "input" && var[var.length-2]!="/"){
        var= var.slice(0, var.length-1)+"/"+var[var.length-1]
        }
    
    Login or Signup to reply.
  2. Consider running the copied html source string through a tool like html tidy. If you’d like to do the formatting in the browser, consider prettier. See example below. Good Luck!

      const output = prettier.format("<input type='text' name='username'>", {
        parser: "html",
        plugins: prettierPlugins,
      });
    
      // Send to server or update your clipboard.
      console.log(output)
    <script src="https://unpkg.com/[email protected]/standalone.js"></script>
    <script src="https://unpkg.com/[email protected]/parser-html.js"></script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search