Amir-Mousavi
Amir-Mousavi

Reputation: 4563

Conditional input placeholder with special characters (HEX value)

How can I render the placeholder conditionally which returns the character, not the string value itself?

Why the second input placeholder interpreted as special char, while the first one as a string

class App extends React.Component{
  render(){
    const {mode} = this.props;
    return(
      <div>
      <div><input type="password" placeholder={mode ?"pass":"&#x25CF;&#x25CF;&#x25CF;&#x25CF;"} /></div>
<input type="password" placeholder="&#x25CF;&#x25CF;&#x25CF;&#x25CF;"/>
</div>
    )
  }
}

ReactDOM.render(
  <App mode={false}/>,
  document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Upvotes: 3

Views: 925

Answers (1)

keikai
keikai

Reputation: 15146

As the comment said, we can directly use the symbol.

And there is another programmatic solution: DOMParser()

The DOMParser interface provides the ability to parse XML or HTML source code from a string into a DOM Document.

const yourText = `&#x25CF;`

const parser = new DOMParser();
const text = parser.parseFromString(yourText, "text/html").body.textContent;

placeholder={mode && text}

See more examples here:

const App = () => {
const InputMode0 = () => {
  return (
    <div>
      <input type="password" placeholder="&#x25CF;&#x25CF;&#x25CF;&#x25CF;" />
    </div>
  );
};
const InputMode1 = ({ mode }) => {
  const parser = new DOMParser();
  const text = parser.parseFromString(
    `&#x25CF;&#x25CF;&#x25CF;&#x25CF;`,
    "text/html"
  ).body.textContent;
  return (
    <div>
      <input
        type="password"
        {...(mode
          ? { placeholder: text }
          : { placeholder: `&#x25CF;&#x25CF;&#x25CF;&#x25CF;` })}
      />
    </div>
  );
};
const InputMode2 = ({ mode }) => {
  const parser = new DOMParser();
  const text = parser.parseFromString(
    `&#x25CF;&#x25CF;&#x25CF;&#x25CF;`,
    "text/html"
  ).body.textContent;
  return (
    <div>
      <input
        type="password"
        placeholder={mode ? text : `&#x25CF;&#x25CF;&#x25CF;&#x25CF;`}
      />
    </div>
  );
};

return (
  <div className="App">
    <InputMode0 />
    <InputMode1 mode={false} />
    <InputMode1 mode={true} />
    <InputMode2 mode={false} />
    <InputMode2 mode={true} />
  </div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>

Upvotes: 1

Related Questions