Ad

How To Set The Image Position With JSX/HTML5?

- 1 answer

this is a very easy question, but I can not decide what is the cleanest nor actually to get it to work. I have this JSX-part in a reactJS class, and would like to set position dynamically through a prop-value. Which tag attribute should I add to the following code snippet? I have seen examples with style and tried setting left and right etc without any success.

Any help is appreciated.

<img onClick={this.handleKeyPress} src="/image/1" alt="HTML5" width="200" height="200" />
Ad

Answer

JSX is a prepocessor syntax that will essentially create a bunch of React.createElement function calls with the right elements/components passed in to the different calls. So instead of doing React.createElement('div', props, children) for every container/component/piece of markup you want to create. The upside is that you can return component markup that's easy to read and understand but feels more familiar and easy to write than a ton of nested function calls.

There are a few key differences between regular HTML and JSX, though. Most of them stem from the clashes w/ JavaScript reserved words:

  • some attributes are camelCased and named slightly differently, like htmlFor (as opposed to for)
  • style gets passed in to the style property as an object via an outer JSX expression {{}}
  • most css names are different if they use a hyphen, but most just get camelCased. So: marginLeft, paddingRight, and so on
  • you can pass in style props just like you'd pass other props; they just go right into the style object you create for the component/element.
  • custom attributes (created with a hyphen) won't get rendered except for those that follow the aria spec (aria-, etc.)

So, taking that into consideration, your image component might look something like this:

<img onClick={this.handleKeyPress} 
   src="/image/1" 
   alt="HTML5" 
   style={{width: 200, height: 200, position: 'absolute', top: this.props.top, left: this.props.left}}/>

See also:

Ad
source: stackoverflow.com
Ad