Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax to change image source based on states and props in react

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

like image 965
ogk Avatar asked Mar 14 '23 16:03

ogk


1 Answers

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"} />
);
like image 134
Tzach Avatar answered Apr 08 '23 12:04

Tzach