13

This doesn't display an image, but still works as a button.

<button><img src={"./img/google.png"} /></button>

My folder setup is /user/img/google.png and /user/loginGoogle.jsx , so I don't think there is a problem with source

dovla
  • 191
  • 2
  • 4
  • 11

6 Answers6

21

This will work:

<button><img src="./img/google.png" alt="my image" onClick={this.myfunction} /></button>

then if you define:

  myfunction() {
        console.log("CLICKED");
  }

and if you click your image you will see CLICKED appearing in the console.

So if you add the onClick listener to your image it will work. Then you can wrap that image in a button and even add some CSS class to it to match your needs.

Theo
  • 1,165
  • 9
  • 14
  • http://pastebin.com/hnCVFSBs This is what I got now, onSubmit is defined above this, but I still don't get why I don't see the image @Theo – dovla Mar 20 '16 at 14:12
  • the code seems fine. It definitely works for me. Maybe the image url is wrong? What happens if you try this? http://soulsnatcher.bplaced.net/LDRYh.jpg – Theo Mar 20 '16 at 15:35
  • 1
    I just figured it out, it was kind of stupid, images must be in a public folder, I moved them there and now it works, thanks tho – dovla Mar 20 '16 at 15:40
  • my image in my case this is working no need '.' in front of the '/img' – Daniel Wijono Oct 13 '21 at 03:42
1

If you're using React bootstrap button, typescript code work as below.

import { Button } from 'react-bootstrap'

<Button style={{backgroundImage:"url('./images/logo.png')",backgroundSize:"cover", width:"40px", height:"40px"}}></Button>
crystal
  • 185
  • 1
  • 4
1

You can use an 'img' as a button, it has an onClick property. It will also be easier to set hover effects and to do general styling that way.

<img src={<url>} alt=<alt-string> width=<width> height=<height> onClick={() => <onClick function>}/>

Hao
  • 159
  • 1
  • 4
0

Moved all the images to a public folder in my project and now it works

dovla
  • 191
  • 2
  • 4
  • 11
0
<img src={require('/images/myImage.png')} />

make sure to change the file directory and name to your specific file.

Matin
  • 11
  • 2
-2

import logo from './logo.png'; // Tell webpack this JS file uses this image

// Import result is the URL of your image return ;