Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React img tag issue with url and class

I have the following simple react code in my JSX file:

/** @jsx React.DOM */

var Hello = React.createClass({
    render: function() {
        return <div><img src='http://placehold.it/400x20&text=slide1' alt={event.title} class="img-responsive"/><span>Hello {this.props.name}</span></div>;
    }
});

React.renderComponent(<Hello name="World" />, document.body);

The output in the DOM is as follows:

<div data-reactid=".0">
  <img src="http://placehold.it/400x20undefined1" data-reactid=".0.0">
  <span data-reactid=".0.1">
    <span data-reactid=".0.1.0">Hello </span>
    <span data-reactid=".0.1.1">World</span>
  </span>
</div>

I have two issues with it:

  • The image URL is rendered incorrectly, it is rendered as 'http://placehold.it/400x20undefined1'
  • The class on my image disappears

Any ideas?

like image 772
Serge van den Oever Avatar asked Sep 26 '14 07:09

Serge van den Oever


1 Answers

Remember that your img is not really a DOM element but a javascript expression.

  1. This is a JSX attribute expression. Put curly braces around the src string expression and it will work. See http://facebook.github.io/react/docs/jsx-in-depth.html#attribute-expressions

  2. In javascript, the class attribute is reference using className. See the note in this section: http://facebook.github.io/react/docs/jsx-in-depth.html#react-composite-components

    /** @jsx React.DOM */
    
    var Hello = React.createClass({
        render: function() {
            return <div><img src={'http://placehold.it/400x20&text=slide1'} alt="boohoo" className="img-responsive"/><span>Hello {this.props.name}</span></div>;
        }
    });
    
    React.renderComponent(<Hello name="World" />, document.body);
    
like image 190
rowbare Avatar answered Nov 09 '22 16:11

rowbare