Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using CSS transform: translate(...) with ReactJS

According to https://facebook.github.io/react/tips/inline-styles.html

CSS styles need to be passes as an object to the component. However, if you are trying to use transform styles you will get an error.

like image 822
Guy Laor Avatar asked Sep 17 '15 15:09

Guy Laor


People also ask

Can you change CSS With React?

To change the style of an element on click in React:Set the onClick prop on the element. When the element is clicked, set the active state. Use a ternary operator to conditionally set the new styles based on the state variable.

What transform translate do in CSS?

The translate CSS property allows you to transfer an element from one place to another along the X (horizontal) axis, the Y (vertical) axis, and the Z (depth) axis, similar to how you might think of moving an element using offsets, like top , bottom , left , and right .


2 Answers

Translate also wasn't working for me. I fixed it by adding 'px' behind the var.

ES6 code:

render() {     const x = 100;     const y = 100;     const styles = {          transform: `translate(${x}px, ${y}px)`      };      return (         <div style={styles}></div>     ); } 
like image 122
MarvinVK Avatar answered Sep 24 '22 08:09

MarvinVK


My solution was to first concatenate the string and then pass it to the object. Notice the use of 'px' here.

render: function() {      var cleft = 100;     var ctop = 100;     var ctrans = 'translate('+cleft+'px, '+ctop+'px)';     var css = {         transform: ctrans      }      return (          <div style={css} />     ) } 
like image 45
Guy Laor Avatar answered Sep 25 '22 08:09

Guy Laor