0

Dynamically Rendering an image in reactjs.... What I want to do is change an image dynamically when a user selects a new team in my dropdown menu.

<Col xs="6">
         <Label for="name"><h2> Home Team </h2> </Label>
          <Input type="select" name="homeTeam" id="exampleSelect" onChange={this.handleChange}>
            <option>Utah Jazz</option>
            <option>Houston Rockets</option>
            <option>Cleveland Cavaliers</option>
            <option>Boston Celtics</option>
            <option>Golden State Warriors</option>
            <option>Los Angeles Lakers</option>
          </Input>

I am trying to do this by using state as follows:

<Img src={require(this.state.homeImage)} width="100" height="50"/>

or

<Img src={require(this.state.homeImage)} width="100" height="50"/>

But I either get an error saying

Cannot find module "."

or

this is a reserved word

respectively.

The following is the code for my component. I would appreciate any input on how to fix this problem or any new ideas on how to make the same functionality work! Thank you!

import React, { Component } from 'react';
import axios from 'axios';
import { Button, Form, FormGroup, Label, Input, FormText, Row, Col, Container, Dropdown, DropdownToggle, DropdownMenu, DropdownItem } from 'reactstrap';
import ReactDOM from 'react-dom';
import Img from 'react-image'
import 'bootstrap/dist/css/bootstrap.min.css';
import Carousel1 from './HomeCarousel.js';
import Carousel2 from './AwayCarousel.js';
import './nba.css';
import nbaLogo from '../../images/nbaLogo.jpg';






class HomeTeamSelector extends Component {

  constructor(props) {
    super(props)




    this.state = {
      // homeTeam: '',
      // awayTeam: '',
      homeTeam: 'Jazz',
      awayTeam: 'Jazz',
      homeImage: '../../images/nbaLogo.jpg',
      awayImage: 'nbaLogo',
    }


    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }


componentDidMount(){
  // this.setState({
  //   homeImage: 'nbaLogo',
  // })
    this.state.homeImage = '../../images/nbaLogo.jpg';
  // console.log('homeImage: ', this.state.homeImage);
  var image = '../../images/nbaLogo.jpg';
  console.log('image: ',image);
}





    handleChange = e => {
      // this.setState({
      //   [e.target.name]: e.target.value,
      //   homeImage: '../../images/nbaLogo.jpg',
      // })
      this.state.homeImage = '../../images/nbaLogo.jpg';

      console.log('handle change homeImage: ',this.state.homeImage);
      const image = this.state.homeImage
      console.log('image is: ', image);
      this.state.homeImage = image;
    }

    async handleSubmit(e, activeIndex) {
      e.preventDefault()
      // const  { homeTeam } = this.state



      const teams = {
        // homeTeam: this.state.homeTeam,
        // awayTeam: this.state.awayTeam,
        homeTeam: this.state.homeTeam,
        awayTeam: this.state.awayTeam,
      }

      const form = await axios.post('/api/form', {teams});


     }





  render() {
    return (
      <div className="pickerDiv">
      <img src={nbaLogo} width="100" height="50" />
      <Img src={require(this.state.homeImage)} width="100" height="50"/> /// <--- this is the line that i am referring to in my post.
      <p> {this.state.homeImage} </p>
      <h1> {this.state.homeTeam} -vs- {this.state.awayTeam} </h1>
      <Form className="emailForm" onSubmit={this.handleSubmit} style={{ width: '600px'}}>

        <FormGroup id="formElement">

<div id="test">

<Container>
    <Row>

         <Col xs="6">
         <Label for="name"><h2> Home Team </h2> </Label>
          <Input type="select" name="homeTeam" id="exampleSelect" onChange={this.handleChange}>
            <option>Utah Jazz</option>
            <option>Houston Rockets</option>
            <option>Cleveland Cavaliers</option>
            <option>Boston Celtics</option>
            <option>Golden State Warriors</option>
            <option>Los Angeles Lakers</option>
          </Input>

         </Col>
         <Col xs="6">
         <Label for="name"><h2> Away Team </h2> </Label>
         <Input type="select" name="awayTeam" id="exampleSelect" onChange={this.handleChange}>
           <option>Utah Jazz</option>
           <option>Houston Rockets</option>
           <option>Cleveland Cavaliers</option>
           <option>Boston Celtics</option>
           <option>Golden State Warriors</option>
           <option>Los Angeles Lakers</option>
         </Input>



         </Col>
       </Row>
</Container>

</div>

    </FormGroup>



    <Button color="primary">Send</Button>

  </Form>







      </div>
    );
  }



}



export default HomeTeamSelector;
  • Possible duplicate of [webpack dynamic module loader by require](https://stackoverflow.com/questions/42797313/webpack-dynamic-module-loader-by-require) – Andy Ray May 17 '18 at 19:14

1 Answers1

0

You can pass an object with the image depending on state, but you first have to imported with a nickname, something like this:

import foo from '../images/foo.jpg';
import bar from '../images/bar.jpg';

So depending on your state you can do something like this:

class HomeTeamSelector extends Component {

constructor(props) {
super(props)
this.state = {
  homeTeam: 'Jazz',
  awayTeam: 'Jazz',
  switchImage: false,
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange = e => {
   this.setState({
     switchImage: true,   
  })
}
  render() {
  const { swichtImage } = this.state;

   const imagePassedDown = if(switchImage) {
     return foo;
  } else if(!switchImage) {
      return bar;
  }
  };
   return (
    <div className="pickerDiv">
    <img src={imagePassedDown} width="100" height="50"/> 
     <p> {this.state.homeImage} </p>
     <h1> {this.state.homeTeam} -vs- {this.state.awayTeam} </h1>
     <form className="emailForm" onSubmit={this.handleSubmit} style={{ width: '600px'}}>

    );
  }
}



 export default HomeTeamSelector;

Basically what I'm doing is passing an object with the reference to the image that will be different depending on the state (i.e: It will change every time you click on something). That's the basic idea hope it helps :)

manAbl
  • 506
  • 5
  • 21