Yanshof
Yanshof

Reputation: 9926

Can't find a way to change reactjs element position on runtime

I wrote some react.component and i define the position as fixed.
i need to move this element position on runtime and

 render(){
    var t = <div className="myElement" />;
    t.top = '${500}px';
    t.left = '${900}px';

     return t;     // the element position need to be now 500, 900 
 }

Upvotes: 0

Views: 1597

Answers (2)

Rohith Murali
Rohith Murali

Reputation: 5669

For this you can try the following method,

render(){
let newStyle={
  top:500,
  left:900,
  position:"fixed",
}

return <div style={newStyle} />
}

Here you can assign any value at runtime for the location of the element during runtime by setting the value at the place of 500 and 900. Thus making the size dynamic.

Upvotes: 1

Chris
Chris

Reputation: 59491

Seems like you just need to pass some inline css rules:

render(){
  const s = {top: '500px', left: '900px'};
  return (
    <div className="myElement" style={s} />
  );
}

or, the more compact version:

render(){
  return (
    <div className="myElement" style={{top: '500px', left: '900px'}} />
  );
}

React will automatically px if a unit is missing. So you can also do: {top: 500, left: 900}


From the docs:

The style attribute accepts a JavaScript object with camelCased properties rather than a CSS string. This is consistent with the DOM style JavaScript property, is more efficient, and prevents XSS security holes.

Upvotes: 2

Related Questions