Source:  Twitter logo

I have an HTML tag value in my state variable as

this.state = {
    value: '<p>This is a paragraph</p>'
}

I want to display this HTML content in my child component. I'm trying to do as

<Childcomponent value={this.state.value} />

So that i can use the props to access the value inside the child component. My child component is

render() {
    return(
        <div>{this.props.value}</div>
    )
}

But this produces some errors. How can I fix this? Is there any other solution? Thanks in advance.

you should use jsx for this,

const someHtml = (<p>This is a paragraph</p>)

and then pass it to your child component as prop like this (prop type is node)

<Childcomponent value={someHtml} />

and render it like any other variable {value} in the child component

4 users liked answer #0dislike answer #04
Eliran profile pic
Eliran

I wouldn't recommend doing it, but if you know what you are doing, you can use dangerouslySetInnerHTML prop. So, your ChildComponent should be something like

function ChildComponent(props) {
  return <div dangerouslySetInnerHTML={props.value} />
}

But, like I said, I don't recommend doing it, as it can be vulnerable for XSS attacks. You can find more info in React Docs

3 users liked answer #1dislike answer #13
magneticz profile pic
magneticz

I think the approach is wrong here.

Firstly, state should be reserved for values that change or data coming in from an API. I would not say that a html snippet should be part of an applications state.

Eliran suggests an approach, but again whereby the child component is expecting a prop called value.

There is also another way, which is 'children' where you can squirt in html to a child component.

E.g.

<Childcomponent value={somePropToPassDown}>
    <p>This is a paragraph</p>
</ChildComponent>

and in the component itself....

const ChildComponent= (props) => {
    return (
        <div>
            <p>{props.value}</p>
            {props.children}
        </div>
    )
}

Have a read of this article on React Children which explains in more detail

3 users liked answer #2dislike answer #23
Chris Adams profile pic
Chris Adams

Don't set the value as string instead you can set the value dynamically wrapping the text with a html element.

constructor(props) {
 super(props);
 this.state = {
  value: ''
 }
}

componentDidMount = async () => {
 this.setState({
  value: <p>This is a paragraph</p>
 })
}

By this way you can set and render the html element dynamically.

You can also use dangerously set inner html. Here is the link for the reference, https://zhenyong.github.io/react/tips/dangerously-set-inner-html.html.

1 users liked answer #3dislike answer #31
laxman khanal profile pic
laxman khanal

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).