Jeff
Jeff

Reputation: 14279

Unable to pass image as prop using {}. Must use <>

Gatsby 2.4.11

I have a component that embodies a section on my site (source at the bottom). I am including the Section component on pages,

import SomeIcon from '../images/icons/something.svg'

const SomePage = () => (
  <Section title="Lorum Ipsum" icon=<SomeIcon/>>
    <p>Lorum ipsum dolor sit amet</p>
  </Section>
)

This works and renders the page properly. However, that syntax icon=<SomeIcon/> deeply offends me down to my core. Plus it is tripping up the syntax checker and syntax coloring of my text editor. I want to switch it to {}

<Section title="Lorum Ipsum" icon={SomeIcon}>

Yet with this syntax, the icon doesnt render. It's just blank. How do I pass an image as a property with the squiggles {}?


Section.js

import React from 'react'
import PropTypes from 'prop-types'

const Section = ({ children, icon, title, background, fullWidth }) => (
  <section style={{background:background}}>
    <div class="wrap">
      <h2>{title}</h2>
      <span class="icon">{icon}</span>
      <div class="content">
        {children}
      </div>
    </div>
  </section>
)

Section.propTypes = {
  title: PropTypes.string,
  icon: PropTypes.string,
  background: PropTypes.string,
  fullWidth: PropTypes.boolean,
}

Section.defaultProps = {
  title: ``,
  icon: ``,
  background: ``,
  fullWidth: false,
}

export default Section

Upvotes: 0

Views: 45

Answers (1)

bitsapien
bitsapien

Reputation: 1833

That's some pretty neat refactoring. You should probably try doing this instead to make it work. This is because when you pass a component as a prop, it goes in uninstantiated. It needs to be instantiated inside.

Section.js

import React from 'react'
import PropTypes from 'prop-types'

const Section = ({ children, icon, title, background, fullWidth }) => (
  <section style={{background:background}}>
    <div class="wrap">
      <h2>{title}</h2>
      <span class="icon">{icon()}</span>  {/* Notice this line */}
      <div class="content">
        {children}
      </div>
    </div>
  </section>
)

Section.propTypes = {
  title: PropTypes.string,
  icon: PropTypes.func,                  // Notice this line
  background: PropTypes.string,
  fullWidth: PropTypes.boolean,
}

Section.defaultProps = {
  title: ``,
  icon: ``,
  background: ``,
  fullWidth: false,
}

export default Section

Upvotes: 1

Related Questions