0

(SOLVED, see answer below)

I want to add an image inside each accordion section and I've tried to use <img src={Image}/>. If that piece of code is placed as in the screenshot it works, but it's located outside of the < Accordion >.

If I move the code inside < Accordion > it stops working and I can't figure out exactly how to fix this. A thought was to somehow use image like {props.title} and {props.content} but could not get it to work.

Any suggestions?

code in component FirstAccordion.js

Accordion.js // component with the accordion logic

return (
        <div className="accordion-section">
            <button className={`accordion-button ${setActive}`} onClick={toggleAccordion}>
                <p className="accordion-title">{props.title}</p>
                    <Chevron
                        className={`${setRotate}`}
                        width={10}
                        fill={"#777"}
                    />
            </button>
        
            <div 
                ref={content}
                className="accordion-content"
                style={{ maxHeight: `${setHeight}` }}>
            
            <div
                className="accordion-text"
                // the prop dangerouslySetInnerHTML makes it possible to use HTML within a string
                dangerouslySetInnerHTML={{ __html: props.content }}  
                />

            </div>
        </div>

FirstAccordion.js // component in which I import accordion logic

export function FirstAccordion() {
    
    return (
        <>
        <Sidebar />
        <Navbar />
        <h1 className="h1-accordion">Pregnancy Week By Week</h1>
        <section className="accordion-background">
        <div className="accordion-wrapper">
        <div className="accordion-container-cne">
            <Accordion
            title="Week 1"
            content="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."/>
  • It appears that your `Accordion` component needs to accept the `children` prop if you wish to surround HTML/React components in JSX. For example: ```Hello```, the string "Hello" would be accessible as `props.children` or `children` (if you're using ES6 destructuring) within the Accordion component. See this [question](https://stackoverflow.com/questions/49706823/what-is-this-props-children-and-when-you-should-use-it) for more info. – Matt Carlotta Feb 11 '21 at 22:31

1 Answers1

0

Change this:

<div
  className="accordion-text"
  dangerouslySetInnerHTML={{ __html: props.content }}
/>

Too:

<div className="accordion-text">{props.children}</div>

You should then be able to use the accordion like this:

<Accordion title="Week 1">
  <p>Hello World</p>
  <img src={...} />
</Accordion>

You probably have to adjust to your needs.

Mellet
  • 1,196
  • 1
  • 10
  • 14