Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - Prop is undefined in stateless function

I am passing props from one stateless function to another, and I get a reference error saying the prop is undefined. Here is the parent function:

const Home = () => {
  return (
    <App>
      <BackgroundImage url="mercedes-car.jpg">
        <h1>Test</h1>
      </BackgroundImage>
    </App>
  )
}

And here is the BackgroundImage function:

const Image = styled.div`
  background-image: ${props => url(props.imageUrl)};
  background-size: cover;
  height: 100%;
  width: 100%;
`;

const BackgroundImage = (props) => {
    console.log(props)
  return (
    <Image imageUrl={ props.url }>
      { props.children }
    </Image>
  )
}

The error is that url is undefined; however, when I console.log(props), I get an object with url and children. Any direction or explanation as to why this error is throwing would be appreciated!

like image 594
Nic Bonetto Avatar asked Mar 14 '18 00:03

Nic Bonetto


2 Answers

I'm guessing you meant

background-image: ${props => url(props.imageUrl)};

to be

background-image: url(${props => props.imageUrl});

since the result of that function needs to be a string. Otherwise you're trying to call a function called url.

like image 97
loganfsmyth Avatar answered Nov 09 '22 22:11

loganfsmyth


you have a scope issue. change it to:

const BackgroundImage = (props) => {
  console.log(props)
  const Image = styled.div`
    background-image: url(${props.url});
    background-size: cover;
    height: 100%;
    width: 100%;
  `;

  return (
    <Image>
      { props.children }
    </Image>
  )
}

basically the props are not available to your image, because styled.div is not a normal react component that has props.

Another way is to leave your code as is but set the background image from inside the return function:(and remove it from the styled.div)

  return (
    <Image style={{backgroundImage: `url(${props.url})`}}>
      { props.children }
    </Image>
  )
}
like image 41
Tomer Almog Avatar answered Nov 09 '22 21:11

Tomer Almog