Home > Back-end >  React: Passing functions to child component
React: Passing functions to child component

Time:10-11

Im new to React and going through some basic online tutorials. I am trying to pass a function down from a parent to child component, however does not seem to be working, gives me an undefined value when I console.log the id, the id in the box also disappears when clicked. Can someone point out where Im going wrong please? thanks in advance.

Here is my code:

  • main.jsx
    import React from "react";
    import { useState } from "react";
    import { Box } from "../boxes/box";
    import "./main.css";
    import boxData from "./../data/boxes-data.json";
    
    export function Main() {
    
        const [boxes, setBoxes] = useState(boxData);
    
        function updateBox(boxId) {
            setBoxes((prevBoxes) => {
                return prevBoxes.map((box) => {
                    console.log(box.id);
                    return (box.id === boxId) ? { ...prevBoxes, on: !box.on } : box
                })
            });
        }
    
        return (
            <main className="main">
                <div className="container">
                    <div className="row">
                        <div className="box--container">
                            {boxes.map((box, i) =>
                                <Box
                                    key={i}
                                    {...box}
                                    handleUpdateBox={(event) => updateBox(box.id)}
                                />
                            )}
                        </div>
                    </div>
                </div>
            </main>
        )
    }
  • box.jsx
    import React from "react";
    import './box.css';
    export function Box(props) {
    
        const styles = {
            backgoundColor: (props.on) ? "red" : "black"
        }
    
        return (
            <div
                style={styles}
                className="box"
                onClick={props.handleUpdateBox}
            >
                {props.id}
            </div>
        )
    }
  • data
     [
        {
            "id": 1,
            "on": true
        },
        {
            "id": 2,
            "on": false
        },
        {
            "id": 3,
            "on": true
        },
        {
            "id": 4,
            "on": false
        },
        {
            "id": 5,
            "on": false
        },
        {
            "id": 6,
            "on": true
        }
    ]

CodePudding user response:

in updateBox function you are inserting prevBoxes into the updated box object so your function should change into this

function updateBox(boxId) {
            setBoxes((prevBoxes) => {
                return prevBoxes.map((box) => {
                    console.log(box.id);
                    return (box.id === boxId) ? { ...box, on: !box.on } : box
                })
            });
 }
  • Related