Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can only set one of `children` or `props.dangerouslySetInnerHTML`

Tags:

reactjs

I'm trying to set the inner HTML of an alert div, but receiving the error message : Can only set one of 'children' or props.dangerouslySetInnerHTML'.

Why does this happen ?

function alertContent(alert) { return {__html: alert.text} }

const Alerts = ({ alerts=[{level: 'warning', text:'<p>Warning message!</p>'}], onDismiss }) => (
    <div className="alerts">
        {alerts.map(alert =>
            <Alert
                bsStyle={alert.level}
                key={alert.id}
                onDismiss={onDismiss}
                dangerouslySetInnerHTML={alertContent(alert)} 
                ></Alert>
        )}
    </div>
)
like image 942
Brachamul Avatar asked Apr 22 '16 07:04

Brachamul


2 Answers

I had this error message in a react application.

My issue was I had code as below

<p dangerouslySetInnerHTML={{ __html:stringContainingHtml}}> </p>

My issue was the space in the <p> </p> tags - since html gets injected inside these tags the space was causing an issue as it wasn't empty.

Hope this might help some people.

like image 117
Sprose Avatar answered Sep 21 '22 10:09

Sprose


This happens because dangerouslySetInnerHTML can only be applied to one element. In your case, <Alert/> is a complex element made up of multiple children. That being said, the BS Alert component does accept HTML:

<Alert bsStyle="warning">
  <strong>Holy guacamole!</strong> Best check yo self, you're not looking too good.
</Alert>

or

<Alert bsStyle="warning">
  <span dangerouslySetInnerHTML={alertContent(alert)} />
</Alert>
like image 41
cyberwombat Avatar answered Sep 19 '22 10:09

cyberwombat