Reputation: 4563
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":"●●●●"} /></div>
<input type="password" placeholder="●●●●"/>
</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
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 = `●`
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="●●●●" />
</div>
);
};
const InputMode1 = ({ mode }) => {
const parser = new DOMParser();
const text = parser.parseFromString(
`●●●●`,
"text/html"
).body.textContent;
return (
<div>
<input
type="password"
{...(mode
? { placeholder: text }
: { placeholder: `●●●●` })}
/>
</div>
);
};
const InputMode2 = ({ mode }) => {
const parser = new DOMParser();
const text = parser.parseFromString(
`●●●●`,
"text/html"
).body.textContent;
return (
<div>
<input
type="password"
placeholder={mode ? text : `●●●●`}
/>
</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