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
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):
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!