Ad

Syntax To Change Image Source Based On States And Props In React

- 1 answer

I have a parent component that contains a child component:

return(
  <ChildComponent state={this.getState} />
);

Inside m child component:

return(
  <Avatar src="./picture" />
);

I want to change the source based on the state of the parent. For example if the state of the parent was 1 i the source will be picture1 or if the state was 2 the source would be picture2 and if the state was 3 it would be picture 3. I'm not sure what the syntax would be to complete the child's image source. Would it be something like this:

<Avatar src="'./picture' + this.props.state + '.jpg'"/>

EDIT: just wanted to make it clear I am using a material UI component called avatar. (changed img to avatar) Documentation: http://www.material-ui.com/#/components/avatar

Ad

Answer

The child component should not get the state from the parent, but the props:

return(
  <ChildComponent number={this.state.number} />
);

Then you can use the props to construct a source (notice that the number prop is a javascript expression and not a string like in your example):

return(
  <Avatar src={"./picture" + this.props.number + ".jpg"} />
);
Ad
source: stackoverflow.com
Ad