DennisTurn
DennisTurn

Reputation: 139

Changing image onClick with React

EDIT: Got this working wrapping it in a div. Anyone know why?

I have this image on my Jade (index.jade) template:

img(id='favourite-item')

And this React code:

var FavouriteItemButton = React.createClass({
    getInitialState: function () {
        return {favourite: false};
    },
    handleClick: function (event) {
        this.setState({favourite: !this.state.favourite});
    },
    render: function() {
        var icon = this.state.favourite ? 'images/item-active-empty-heart-icon.png' : 'images/item-active-full-heart-icon.png';
        return (
            <div onClick={this.handleClick}>
            <img
                src={icon}
                width='22' height='20'
            /></div>
        );
    }
});

React is rendering the image but at size: width=0, height=0, like so:

<img id="favourite-item">
     <img src='images/item-active-full-heart-icon.png' width='22' height='20' />
</img>

Questions:

1) Why is React rendering two images? Is this because React is for DOM elements and not images?

2) Why is my image not showing? I personally think it's because the parent image is covering the image inside.

3) Is React appropriate for this? Or should this be done in something like jQuery?

Any ideas are welcome.

Upvotes: 1

Views: 7658

Answers (1)

user1641172
user1641172

Reputation:

React isn't creating two images, jade is creating an image tag and using it as a wrapper for the React image, so this is more of a question of outputting valid html, than one of a problem with React or Jade.

In HTML the <img> tag has no end tag.

You are getting Jade to create an <img> tag but placing the react image inside that image:

<img id="favourite-item">
     <img src='images/item-active-full-heart-icon.png' width='22' height='20' />
</img>

If you change the Jade template wrapper to be a valid container, then it will work, also probably specify the units of measure so the browser doesn't have to guess:

div(id='favourite-item')    

will give you:

<div id="favourite-item">
     <img src='images/item-active-full-heart-icon.png' width='22px' height='20px' />
</div>

Upvotes: 3

Related Questions