S
S
SpbSprut2016-12-07 18:55:35
Twig
SpbSprut, 2016-12-07 18:55:35

How to solve the problem with rendering a string in reactjs (backslashes, html, special characters)?

Let's say there is a line in the database (let's say a comment from the user)

ssss\ss<script>alert(123)</script>ss\\ssssss\\\sssss\\\\sssss\\\\\ssss

It is necessary to display this comment ALSO as it is from the user.
So far the best solution I've come up with is:
file[ test.twig ]
<div id="content"></div>

<script type="text/javascript">
        var comment = '{{ comment|e('html')|e('js') }}';
</script>

file[react.js]
class H1 extends React.Component {
    render() {
        return <div dangerouslySetInnerHTML={{__html: this.props.comment}}></div>;
    }
}

ReactDOM.render(
    <H1 comment={comment} />,
    document.getElementById('content')
);

If you do not use e('js') then the problem with backslashes in js comes out, if you do not use e('html') before e('js') then html tags are cut off
I will be satisfied with the solution from both twig and reactjs . It is necessary that the line is displayed after render in reactjs just as it is. Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
SpbSprut, 2016-12-07
@SpbSprut

so I seem to be too clever
here is a more beautiful option

<script type="text/javascript">
        var comment = '{{ comment|e('js') }}';
</script>

then you can in react as standard
class H1 extends React.Component {
    render() {
        return <h1>{this.props.comment}</h1>;
    }
}

you can look at it without nausea

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question