0

I have a component which displays info supplied in props.

Is there a way to programmatically navigate to this component and pass to him jsx code?

With simple string (not jsx) I would do something like the following:

this.props.history.push("/mycomponent", { message: "Just a text" });

and in target component:

const {message} = this.props.location.state;

However, if I include in message any jsx node, ie. Smiley <i className="far fa-smile"/> it displays as plain text.

Is there any way to achieve this other than using dangerouslySetInnerHTML? If not is it safe to use it in this context?

class MyComponent extends Component {
    returnMessage = () => {
        // this.props.location.state.message = 'Smiley <i className="far fa-smile"/>'
        return {__html: this.props.location.state.message};
    }
    render() {
      return <div dangerouslySetInnerHTML={returnMessage()} />;
    }
}

export default MyComponent;
MrSegFaulty
  • 535
  • 6
  • 10
  • can you not just render like this since it's just a string? `return
    {this.props.location.state.message}
    ` [edit] oh I see you want to also include html
    – Michael Sorensen May 21 '18 at 23:56
  • I like the answer I found https://stackoverflow.com/questions/46832912/is-dangerouslysetinnerhtml-the-only-way-to-render-html-from-an-api-in-react – Michael Sorensen May 22 '18 at 00:11
  • While there are other ways to parse that string into html (or jsx) they really run into the same vulnerabilities where a user might inject a script tag or something malicious. So if you just sanitize your data and make your back end safe you should be g2g. – Michael Sorensen May 22 '18 at 00:13
  • @MichaelSorensen Indeed. I guess the initial title has misled you. Sorry. – MrSegFaulty May 22 '18 at 00:14

0 Answers0