Home > Software design >  How to pass props from child to parent?
How to pass props from child to parent?

Time:09-02

I am new to React and this is the tic tac toe game, i have to pass props from child to parent in this case. I want to get each box value to board component and do some algorithm.

Here is my parent component;

import React from "react";
import Square from "./Square"

export default function Board() {
    return (
        <div className="game-board">
            <Square key="1" />
            <Square key="2" />
            <Square key="3" />
            <Square key="4" />
            <Square key="5" />
            <Square key="6" />
            <Square key="7" />
            <Square key="8" />
            <Square key="9" />
        </div>

Here is my child component;

import React from "react";

export default function Square() {
    const [value, setValue] = React.useState()
    const [mutate, setMutate] = React.useState(false)

    function handleClick() {
        !mutate && setMutate(true)
    }
    return (
        <div className="square" onClick={handleClick}>{value}</div>
    )
}

CodePudding user response:

Properties should not be passed upward. That's a violation of fundamental application principles. Instead, pass a function down which updates the state. See Lifting State Up.

Parent:

const doSomeWork = () { // update app state } 

<Square key="1" onSomeAction={doSomeWork} />

Child:

onClickOrWhatever={props.onSomeAction}

CodePudding user response:

you can use useimperativehandle hook to expose values from child to parent.

  • Related