Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: How to pass function as props from Functional Parent component to child

Parent Component:

const initialValue_modalProps = [
    { show: false, response: "" }
  ];
const [modalProps, setModalProps] = useState(initialValue_modalProps)
const passedFunction = () => {
    setModalProps(modalProps => initialValue_modalProps);
  }
..
..
 <div>
        <Modal show={modalProps.show}
          response={modalProps.response}
          passedFunction={passedFunction}></Modal>
 </div>

Child Component:

export default function ModalComp(props) {
    const [modalOpen, setmodalOpen] = useState(true);
    console.log('modalOpen', modalOpen);
    if (props.show === false || modalOpen === false) {
        return null;
    }
    return (<Modal isOpen={props.show}>
        <ModalHeader>Deployment Status</ModalHeader>
        <ModalBody>{props.response}</ModalBody>
        <ModalFooter>
            <Button onClick={() => {
                setmodalOpen(modalOpen => false);
                props.passedFunction();
            }}>Close</Button>
        </ModalFooter>
    </Modal>)

}

Here I want to passedFunction function from Parent to child so that the Child component can execute it to reset the state in parent

like image 479
Soumitra Bhattacharyya Avatar asked Mar 29 '20 14:03

Soumitra Bhattacharyya


People also ask

How do you pass a function from parent to child in react functional component?

First, you'll need to create two components, one parent and one child. Next, you'll import the child component in the parent component and return it. Then you'll create a function and a button to trigger that function. Also, you'll create a state using the useState Hook to manage the data.

Can we pass function as a prop in react?

To pass a function as props in React TypeScript: Define a type for the function property in the component's interface. Define the function in the parent component. Pass the function as a prop to the child component.

How to pass props from a child component to parent component?

Thus, we can see there is no way to pass props from a child component to a parent component. However, we can always pass around functions from the parent to child component. The child component can then make use of these functions.

Can you pass a function from parent component to child component?

However, we can always pass around functions from the parent to child component. The child component can then make use of these functions. The function can then update the state in a parent component, as we saw above. Once our state gets changed, it is passed down as props again.

Why can't I set props in ReactJS?

The other thing we can see is that React's props are read-only—that is, we do not have any way to set props (it was possible to do that earlier). This behavior makes sense because the purpose of props is just to pass data from one component to another, i.e., only from a parent component to a child component.

What is the use of child component in react?

The child component just consumes that data as props. Also, the child component re-renders whenever the incoming props get updated. Thus, every time our props or state get changed, the rendering of the corresponding component gets triggered again.


Video Answer


2 Answers

You can take this as an reference with live example demo https://codesandbox.io/s/modal-6fvyx

function App() {
  const [status, setState] = React.useState(false);
  const [text, setText] = React.useState("");

  const handleClick = () => {
   setState(prevStatus => !prevStatus);
  };
  const handleChange = e => {
   setText(e.target.value);
  };


  return (
    <>
      <button onClick={handleClick}>Open photo entry dialog</button>
      <ChildComponent
        isOpen={status}
        text={text}
        handleChange={handleChange}
        handleClick={handleClick}
      />
    </>
  );
}

const ChildComponent = ({ isOpen, text, handleChange, handleClick }) => {
  return (
    <>
      {isOpen && (
        <Model
          status={isOpen}
          handleClick={handleClick}
          text={text}
          handleChange={handleChange}
        />
      )}
    </>
  );
};
like image 152
akhtarvahid Avatar answered Oct 19 '22 02:10

akhtarvahid


You need to remove the parentheses behind passedFunction, because otherwise you are executing the function first and passing the result to the child afterwards. Pass your function as it is via passedFunction={passedFunction}.

const ParentComponent = () => {

  const initialModalProps = { ... };
  const [modalProps, setModalProps] = useState(initialModalProps);

  const passedFunction = () => {
    setModalProps(initialModalProps);
  }

  return (
    <div>
      <Modal
        show={modalProps.show}
        response={modalProps.response}
        passedFunction={passedFunction} />
    </div>
  );

};
like image 21
Kluddizz Avatar answered Oct 19 '22 03:10

Kluddizz