Friday, 15 November 2024

How to Pass Functions as component Properties in React?

You can pass a function as a prop to a React component. This is a common practice in React to allow parent components to communicate with child components, such as passing event handlers or callback functions to trigger actions in the parent component.

 

Step 1: Go to the post (Quickly Set Up a React Project with Vite: A Step-by-Step), and set up a React Project ‘pass-function-as-property’.

 

Project structure looks like below.

 


Step 2: Create components folder in src/ folder and define UserDetails Component.

 

UserDetails.jsx

export default function UserDetails(props){
    alert(props.info());

    return <div>
        <ul>
            <li>username : {props.username}</li>
            <li>email : {props.email}</li>
        </ul>
    </div>
}

Step 3: Update src/main.jsx file like below.

 

main.jsx

import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import UserDetails from './components/UserDetails'

let userDetails = {
  username : "Krishna",
  email : "krishna@abc.com",
  info : function(){
    return `Hi, My name is ${this.username}, you can contact me at ${this.email}`;
  }
}
createRoot(document.getElementById('root')).render(
  <StrictMode>
    <UserDetails {...userDetails}/>
  </StrictMode>,
)

As you see above snippet, info function is attached to userDetail property, same is consumed in UserDetails component (Refer UserDetails.jsx file).

 

Step 4: Build and run the application.

cd pass-function-as-property
npm install
npm run dev

Open the url ‘http://localhost:5173/’ in browser, you will see an alert box like below.



Click on OK button, you will see this alert box again.

 


Finally, you can see the below screen.

 


Why the Alert box appear twice?

The prompt box is appearing twice in the code because React.StrictMode intentionally renders components twice (in development mode only) to help identify potential side effects and issues related to component lifecycle. This is a feature designed to detect problems like:

 

1.   Unintended side effects.

2.   Unsafe component lifecycles.

3.   Deprecated APIs.

When the UserDetails component mounts, the alert(props.info()) line is executed. Since StrictMode re-renders the component twice in development, the alert() will be called twice, resulting in the prompt box showing up twice.

 

How to Fix the Issue?

If you want to avoid the alert being triggered twice while keeping StrictMode, consider using console.log() for development debugging, as it won't block or interrupt your workflow with multiple prompts.

 

Alternatively, if you want to prevent StrictMode from re-rendering your components twice, you can temporarily remove StrictMode like this.

 

However, it is recommended to keep StrictMode during development to catch potential bugs early on, but avoid actions like alert() or side-effect-inducing operations inside the render or lifecycle methods of components.

 

You can download this application from this link.




Previous                                                    Next                                                    Home

No comments:

Post a Comment