Guy Laor
Guy Laor

Reputation: 597

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.

Upvotes: 44

Views: 159538

Answers (6)

atazmin
atazmin

Reputation: 5707

This worked for me:

 transform: 'translateX(-100%)',

Upvotes: 5

ninjastarr
ninjastarr

Reputation: 31

This can be done using string template literals ` as your value for the transform key:

const styles = {
logo: {
    transform: `translateX(20px)`
},

function Navbar() {
    return (
        <nav style={styles.nav}>
            <div style={styles.wrapper}>
                <p className="logo" style={styles.logo}>Hello</p>
            </div>

For more on template literals: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Upvotes: 3

Mabroor Ahmad
Mabroor Ahmad

Reputation: 42

You can use translate as a property react provides all translate without specifying transform

style={{
  position: "fixed",
  bottom: "0px",
  left: "50%",
  maxWidth:'450px',
  zIndex: 1,
  translateX:'-50%'
}}

Upvotes: 2

Brian Li
Brian Li

Reputation: 3110

If the solutions above aren't working, you can also try formatting the transform differently:

render() {
    const xPx = 50;
    const yPercent = 50;
    return <div style={{transform: `translateX(${xPx}px) translateY(${yPercent}%)`}}></div>
}

Upvotes: 3

MarvinVK
MarvinVK

Reputation: 3073

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>
    );
}

Upvotes: 67

Guy Laor
Guy Laor

Reputation: 597

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} />
    )
}

Upvotes: 13

Related Questions