2

Found very weird ReactJS element systax {..props} in mesh element, Why is {...props} inside "mesh", Usually if there is then it can have properties but in this case its taking {..props}, How does this systax work and what is it doing with {..props}, Is it declaring it ? Can props be used in rest of element like <mesh {...props} att="{props.el}" />

 const ref = useRef()
  // Hold state for hovered and clicked events
  const [hovered, hover] = useState(false)
  const [clicked, click] = useState(false)
  // Subscribe this component to the render-loop, rotate the mesh every frame
  //useFrame((state, delta) => (ref.current.rotation.x += delta))
  // Return the view, these are regular Threejs elements expressed in JSX
  return (
    <mesh
      {...props}
      ref={ref}
      scale={clicked ? 1.5 : 1}
      onClick={(event) => click(!clicked)}
      onPointerOver={(event) => hover(true)}
      onPointerOut={(event) => hover(false)}>
      <boxGeometry args={[2, 2, 2]} />
      <meshBasicMaterial color={hovered ? 'hotpink' : 'brown'} />
    </mesh>
  )
}
user204069
  • 1,215
  • 3
  • 19
  • 25
  • https://react.dev/learn/passing-props-to-a-component#forwarding-props-with-the-jsx-spread-syntax – adsy Apr 13 '23 at 19:47
  • Does this answer your question? [How to pass all other props to react class?](https://stackoverflow.com/questions/41534160/how-to-pass-all-other-props-to-react-class) – Konrad Apr 13 '23 at 20:24

1 Answers1

0

This is a spread operator used for passing multiple properties at once into a Component.

As Properties at the right side override those further left, also the positioning of the spliced content is important. Here, at first position, setting a Property explicit again will override the spliced one. For example:

const Box = (): JSX.Element => {

    const props = {
        a: "a",
        b: "b",
    }

    return <Mesh {...props} a="override" />;
};

type TestProps = {
    a: string,
    b: string,
}
const Mesh = ({ a, b }: TestProps): JSX.Element => {
    return <>{`${a} ${b}`}</>;
}

will result in setting 'a' to 'a' from splicing, then overriding with explicit set 'override', resulting in

override b

Passing in

<mesh {...props} att="{props.el}" />

works perfectly, but keep in mind that 'el' as well as 'att' will be passed to the Component:

    const Box = (): JSX.Element => {

        const props = {
            el: "el",
            attr: "attr",
        }

        return <Mesh {...props} attr={props.el} />;
    };

    type TestProps = {
        el: string,
        attr: string,
    } 
    const Mesh = ({ el, attr }: TestProps): JSX.Element => {
        return <>{`${el} ${attr}`}</>;
    }

Results in

el el

For details, also see https://react.dev/learn/passing-props-to-a-component#forwarding-props-with-the-jsx-spread-syntax