Home > Software engineering >  React: Pass function with a given argument to child
React: Pass function with a given argument to child

Time:10-04

My goal is to create a function in a parent component and pass it to the child component, so I can update state from child to parent.

However, I would like to determine one argument in the parent component already.

Is there any way of doing so? See my example below.

Let´s assume I have the following code

const Parent = ( props ) => {
    
    const [counter, setCounter] = useState(0);

    function updateFunc(type, id) {
        let obj = {type : "", id : id}
        if (type == "red"){
            obj.type = 'RED_FLAG';
        } else {
            obj.type = 'ELSE_FLAG';
        }
    return obj;
    }
    
    return (
        <>
            // HERE I WOULD LIKE TO PASS ALSO A "RED" ARGUMENT -> IS THIS POSSIBLE?
            <Child update = {update}
        </>
    )

}

CodePudding user response:

There is a technique called currying. For example, you could have a function that takes the type as an argument and returns a function that takes the id as an argument, which finally returns the object.

const Parent = (props) => {

    const [counter, setCounter] = useState(0);

    function updateFunc(type) {
        return (id) => {
            let obj = { type: "", id: id }
            if (type == "red") {
                obj.type = 'RED_FLAG';
            } else {
                obj.type = 'ELSE_FLAG';
            }
            return obj;
        }
    }

    return (
        <>
            <Child update={update("red")}
        </>
    )

}

CodePudding user response:

You can do that by making an additional function:

<Child update={(id) => {
  return updateFunc("red", id);
}}/>

  • Related