简体   繁体   中英

How to set default value in dangerouslySetInnerHTML in react?

1.Create react component - customhtmlelement

<customelement>
    <div dangerouslySetInnerHTML={{ __html: this.props.customHtml }} />
</customelement>

2.use of react component

<customhtmlelement
 customHtml="<input value={value} disable='true' placeholder='Enter text' type='text' id='test'</input>"/>><<customhtmlelement/>

set default value in text box.

let value= "test";

it's not working. How to set default value in innerHtml ?

try this, It may help

import React from "react";
import ReactDOM from "react-dom";
const value = "test";

// inner HTML Example...
function createMarkup() {
  return {
    __html: "<input value="+value+" disable='true' placeholder='Enter text' type='text' id='test'</input>"
  };
}

//React component...
function MyComponent() {
  return <div dangerouslySetInnerHTML={createMarkup()} />;
}

const rootElement = document.getElementById("root");
ReactDOM.render(<MyComponent />, rootElement);

Why would you render input with dangerouslySetInnerHTML ?

Anyway your code is not really valid.

Try this:

function CustomHTMLElement(props) {
  return <div dangerouslySetInnerHTML={{__html: props.customHtml}} />
}

function App() {
  const value = 'Test Value'

  return (
    <div>
      <CustomHTMLElement
        customHtml={`<input id='test' type='text' placeholder='Enter text' value='${value}' disabled=${true} />`}
      />
    </div>
  )
}

you need to use like this, with the help of template literals

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

let value = "text";

function CustomHtmlElement(props) {
  return <div dangerouslySetInnerHTML={{ __html: props.customHtml }} />;
}

function App() {
  return (
    <div className="App">
      <CustomHtmlElement
        customHtml={`<input value=${value} disable='true' placeholder='Enter text' type='text' id='test'</input>`}
      />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

working example codesandbox

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM