Hareesh
Hareesh

Reputation: 1587

How can I pass HTML as props in ReactJS

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.

Upvotes: 2

Views: 9091

Answers (4)

laxman khanal
laxman khanal

Reputation: 998

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.

Upvotes: 1

Chris Adams
Chris Adams

Reputation: 1454

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

Upvotes: 3

Eliran
Eliran

Reputation: 355

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

Upvotes: 5

magneticz
magneticz

Reputation: 2440

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

Upvotes: 4

Related Questions