Home > Back-end >  Could you please help me why $ is a String and not Identifier in React Js
Could you please help me why $ is a String and not Identifier in React Js

Time:03-20

This line of codes get error

listRef.current.style.transform = 'translateX(${230   distance}px)'

    import { ArrowBackIosOutlined, ArrowForwardIosOutlined } from '@material-ui/icons';
    import React, { useRef } from 'react'
    import "./list.scss";
    import ListItem from "../listItem/ListItem";
    
    export default function List() {
    
      const listRef = useRef()
    
      const handleClick = (direction) => {
        let distance = listRef.current.getBoundingClientRect().x - 50
        if(direction === "left"){
          listRef.current.style.transform = 'translateX(${230   distance}px)'
        }
      }
    
      return (
        <div className='list'>
            <span className="listTitle">Continue to watch</span>
            <div className="wrapper">
                <ArrowBackIosOutlined className="sliderArrow left" onClick={()=>handleClick("left")}/>
                <div className="container" ref={listRef}>
                    <ListItem/>
                    <ListItem/>
                    <ListItem/>
                    <ListItem/>
                    <ListItem/>
                    <ListItem/>
                    <ListItem/>
                    <ListItem/>
                    <ListItem/>
                    <ListItem/>
                    <ListItem/>
                </div>
                <ArrowForwardIosOutlined className="sliderArrow right" onClick={()=>handleClick("right")}/>
            </div>
        </div>
      )
    }

CodePudding user response:

Change you code from

 const handleClick = (direction) => {
    let distance = listRef.current.getBoundingClientRect().x - 50
    if(direction === "left"){
      listRef.current.style.transform = 'translateX(${230   distance}px)'
    }
  }

to

 const handleClick = (direction) => {
    let distance = listRef.current.getBoundingClientRect().x - 50
    if(direction === "left"){
      listRef.current.style.transform = `translateX(${230   distance}px)`
    }
  }

What you need is called template literal in js.

Type Template Literal:

Mac: Shift ` on keyboard

Refer to: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

CodePudding user response:

Can you please provide what is error. I tried your code and css is not working for me 'translateX(${230 distance}px)'. So tried this.

import { useRef } from "react";
import "./styles.css";

export default function App() {
  const ref = useRef();

  const handleClick = () => {
    ref.current.style.transform = "rotate(20deg)";
    console.log(ref.current.getBoundingClientRect().x - 50)
  };
  return (
    <div className="App">
      <h1 ref={ref}>Hello CodeSandbox</h1>
      <h2 onClick={handleClick}>Start editing to see some magic happen!</h2>
    </div>
  );
}
  • Related