Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React returns image src as object

Tags:

reactjs

I have a variable defined like this:

const team = [
  {
    name: "Foo",
    bio: "FooBar",
    image: { foo }
  },
  {
    name: "Bar",
    bio: "FooBar",
    image: { bar }
  },
];

Where the images are imported like this:

import foo from "../assets/foo.jpg";
import bar from "../assets/bar.jpg";

These are then passed to a component to be rendered, with:

<TeamRow team={team} />

The TeamRow component looks like this:

const TeamRow = props => {
  const items = props.team.map((item, index) => {
    return (
      <div className="col-10 col-sm-4 col-md-1 mx-auto text-center">
        <div className="row">
          <div className="col-12 teamMemberImage">
            <img className="img-fluid" src={item.image} />
          </div>
        </div>
        <div className="row">
          <div className="col-12">{item.name}</div>
        </div>
        <div className="row">
          <div className="col-12">{item.bio}</div>
        </div>
      </div>
    );
  });
  return <div className="row">{items}</div>;
};

export default TeamRow;

The images fail to render. When I look at them in the dev tools, they have src="Object object". The class that calls TeamRow, is the class in which team is defined. After defining it, calling console.log(foo returns the url pointing to the image, as expected. Somehow, in being passed to the second component, the expected behaviour ceases.

Strangely, earlier, I was using the react logo as a placeholder. So: import logo from "../assets/logo.svg";, and this worked, but only if I rendered it as src={item.image.logo}.

like image 874
Alex Avatar asked Jan 28 '23 05:01

Alex


2 Answers

{ foo } is shorthand for { foo: foo }, and { bar } is shorthand for { bar: bar }.

Instead of putting the image url in an object with a key that will be different for every image, you can set it as the image property directly.

const team = [
  {
    name: "Foo",
    bio: "FooBar",
    image: foo
  },
  {
    name: "Bar",
    bio: "FooBar",
    image: bar
  },
];
like image 197
Tholle Avatar answered Jan 31 '23 21:01

Tholle


team[0].image is an object on the form {"foo":"yourUrl"} because you've wrapped foo in brackets, which uses the object shorthand syntax to create a property named foo with the value in variable foo. Remove the brackets around foo and bar

like image 27
Jonas Høgh Avatar answered Jan 31 '23 23:01

Jonas Høgh