How to add a function in JSX ?
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
Step 3: After setting up react environment on your system, we can start by creating an App.js file and create a directory by the name of components in which we will write our desired function.
Project Structure: It will look like the following.
Now let’s see how to add a function with JSX.
Example 1: In this example, we will consider an example to demonstrate how can a function be added to our application. Now inside the component’s directory, we will create a display.js file which will contain the display function that is going to be added to the application.
Now, the final step is to incorporate our function in the application. This can be done by importing the function into App.js file and using the name of the function as a custom JSX tag.
Output: Thus, we can see that it is really simple to add functions to our JSX code. The example provided was quite simple but complex rendering and desired calculations can also be done inside functions and then can be used in our application code.
Example 2: Now in this example, we will create display.js file with a change. This time we will be able to change the contents of the header from App.js file.
Now, We will now incorporate the function in the App.js file as we did in the previous example.
From the code, we can predict the output now. Note that you can render your customized output by just changing the name property in the tag.