Victor Deb
Victor Deb

Reputation: 1

Put image as an object into state variable and pass it as a props

I was trying to put an image as an object into state and pass the state as a props in react but it's not passing anything.

import xaprikaScreen from "./images/xaprikaScreenShot.jpg";
import linguadenScreen from "./images/linguadenScreenShot.jpg";

export class Portfolio extends Component {
  constructor() {
    super();
    this.state = {
      currentProject: 0,
      projects: [
        {
          id: 1,
          projectName: "Linguaden.com",
          projectLink: "www.linguaden.com",
          githubLink: "",
          displayPicture: { linguadenScreen },
          projectDescription: ""
        },
        {
          id: 2,
          projectName: "Xaprika.com",
          projectLink: "www.Xaprika.com",
          githubLink: "",
          displayPicture: { xaprikaScreen },
          projectDescription: ""
        }
      ]
    };
  }

render() {
    return (
    <Projects imageSource={this.state.projects[this.state.currentProject["displayPicture"]}/>
);
}
}
}

Here i have imported 2 images as an object, then i have assigned them into state and then i am trying to pass those variables as props.

Upvotes: 0

Views: 62

Answers (1)

kognise
kognise

Reputation: 632

The problem here is that you're doing this.state.currentProject["displayPicture"]. The value of currentProject is 0, and 0.displayPicture is undefined. You're then doing this.state.projects[this.state.currentProject["displayPicture"], which not only doesn't have a closing bracket, even if it did that would be equivalent to this.state.projects[undefined] which is also undefined.

Replace your render function with the below code and it should work.

render() {
  return (
    <Projects imageSource={this.state.projects[this.state.currentProject].displayPicture} />
  );
}

Upvotes: 1

Related Questions