I have some code to Regex some text and wrap it in a <span />
like so:
highlightQuery() {
// will output the text response from the Model, but also highlight relevant words if they match the search query
// that the user input
let input = this.props.model.get('value');
if(!this.state.hasMatch){
return input;
}
let query = this.props.matched.query,
index = this.props.model.get('searchIndexes')[this.props.matched.index];
const replaceBetween = (str, start, end, what) => {
return str.substring(0, start) + what + str.substring(start + end);
};
let ret = replaceBetween(input, index, query.length, `<span class='highlighted'>${query}</span>`);
return ret;
},
render() {
const classes = classNames(
this.props.model.get('type'),
'character'
);
return (
<span key={this.props.model.cid} className={classes} dangerouslySetInnerHTML={ {__html: this.highlightQuery()} }>
{!this.state.hasMatch && this.highlightQuery()}
</span>
);
}
However, this yields: Uncaught Error: Invariant Violation: Can only set one of children or props.dangerouslySetInnerHTML.
How am I best to conditionally use dangerouslySetInnerHTML
?
However, if the application or site accepts multiple users' data input, you should be concerned. However, apart from that, there is one alternative to using dangerouslySetInnerHTML, simply setting innerHTML of a React HTML element using vanilla JS instead.
dangerouslySetInnerHTML is a property that you can use on HTML elements in a React application to programmatically set their content. Instead of using a selector to grab the HTML element, then setting its innerHTML , you can use this property directly on the element.
The name dangerouslySetInnerHTML is intentionally chosen to remind you that it's dangerous and may cause XSS vulnerabilities so that you make sure your HTML is sanitized before you insert it in your react app.
In React we can access the DOM element using Refs. Refs provide a way to access DOM nodes or React elements created in the render method. Creating Refs: Refs are created using React. createRef() and attached to React elements via the ref attribute.
and make sure you do not include a space between the span tags else you would run into the following error:
invariant.js:39 Uncaught Invariant Violation: Can only set one of
children
orprops.dangerouslySetInnerHTML
.
return = <span key={this.props.model.cid} className={classes} dangerouslySetInnerHTML={ {__html: this.highlightQuery()} }>NO SPACE OR TEXT HERE</span>
You can use spread syntax if you are using ES2016.
const options = {};
if (useHTML) {
options.dangerouslySetInnerHTML = {__html: yourHTML};
} else {
options.children = [<ChildNode/>];
}
return <span {...options} className="myClassName"></span>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With