How to render html inside a functional component in React?

Asked

Viewed 532 times

0

I’m using the version 16.12.0 React. I own a functional Component called Card and would like to insert html into it (I would like to not change its source code).

Card:

function Card ({cardHeader, cardBody, cardDescription}){

return (
    <>
        <div className="card">
            <div className="card-header">
                <h1>{cardHeader}</h1>
                <p>{cardDescription}</p>
            </div>
            <div className="card-body">
                {cardBody}
            </div>
        </div>
    </>
)}

And I would like to move the html further into this component as follows:

 <Card cardHeader={cardTitle} cardBody={object} >
   <div className="card-close">
      ...
   </div>
 </Card>

That way, other places that use the card’s Component won’t need adaptations. Any ideas ?

2 answers

2


You can access through the prop children. For example:

<Card cardHeader={cardTitle} cardBody={object}>
   <div className="card-close"></div> // Essa div é o "children"
</Card>

And in the component <Card>:

function Card ({children, cardHeader, cardBody, cardDescription}){
    return (
        <>
            <div className="card">
                <div className="card-header">
                    <h1>{cardHeader}</h1>
                    <p>{cardDescription}</p>
                </div>
                <div className="card-body">
                    {cardBody}
                    {children} // Exibe o que foi passado como "children"
                </div>
            </div>
        </>
    )
}

See a practical example:

function Componente({ children }) {

  return <div style={{backgroundColor:'red', height: '100px'}}>{children}</div>
}

function Pai() {
  return (
    <Componente>
      <h1>Qualquer HTML</h1>
      <p>Pode ser passado aqui</p>
    </Componente>
  )
}

ReactDOM.render(<Pai />, document.querySelector('#container'));
<div id="container"></div>
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>

1

You need to add an external HTML, right?

You can use the dangerouslySetInnerHTML

 <Card cardHeader={cardTitle} cardBody={object} >
   <div dangerouslySetInnerHTML={{ html: `
      <div className="card-close">
          ...
      </div>
   ` }} />
 </Card>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.