Home > Back-end >  can't pass dynamic props to a child in react
can't pass dynamic props to a child in react

Time:09-04

I am new to React and the project is a moba style game, I have the Map component which listens to clicks and for now i just want to pass the coords from Maps event listener to the Player child component and simply display new coords, unforunately it only passes the initial value, so if my event listener modifies X, the changes dont appear on a child component

import "../Css/Map.css";
import Player from "./Player";

let x = 5;
let y = 5;

function handleClick(event) {

  let currentTargetRect = event.currentTarget.getBoundingClientRect();

  const event_offsetX = event.pageX - currentTargetRect.left,
        event_offsetY = event.pageY - currentTargetRect.top;

  x = event_offsetX.toFixed();
  y = event_offsetY;

  console.log(x, y);
  
}

function Map() {
  return (
    <div className="Map" onClick={handleClick}>
      <Player myProp={x} />

    </div>
  );
}

export default Map;

and the Player component

import "../Css/Player.css";
import image from "../images/tileGrass.png";

const Player = (props) => {

  console.log(props.myProp);
  return (
    <div className="player">
      <img src={image} alt="description" />
      <div>
        <p>{props.myProp}</p>
      </div>
    </div>
  );
}

export default Player;

All I'm trying to achieve now is that when I click on the map somewhere, it gets the new x coord and then passes it down to Player component which updates the paragraph tag, to show that it works. Thanks for any help

CodePudding user response:

In order to propagate your updated x value down to the Player component, React would have to know that the value has changed. It can't know that if you declare it as a local variable. Use a state instead.

import { useState } from 'react';

function Map() {
    const [x, setX] = useState();

    // Move function into component to have access to x/setX
    function handleClick(event) {

        // determine "newX" from mouse

        setX(newX); // by using the state's setter, React knows the value has changed
    }

    return (
        <div className="Map" onClick={handleClick}>
            <Player myProp={x} /> {/* React will now re-render Player when x has changed */}
        </div>
    );
}
   


    
    
  • Related