How to access props inside functional components?
Example 1: Create a file named ‘display.js’ inside components directory and add the following lines of code which contains codes to display the sample text. And then adding Display component in main app for displaying it. Later on, we can pass the text as a props into this file (‘display.js’) and access here in this file (‘display.js’) in next example.
Javascript
// App.js import React from "react" ; import Display from "./components/display" ; function App() { return ( <div> <Display /> </div> ); } export default App; |
Javascript
// display.js import React from "react" ; /* This function contains a sample code for displaying text. Later on, texts can be passed as a props to this component. */ function Display() { return ( <div> <h1> Hello, Welcome to w3wiki! </h1> </div> ); } export default Display; |
Output: The output of the above mentioned code is as follows:
Example 2: Now, we would be passing the data as a props in the functional component. Inside the functional component props are accessed as an argument to the function representing the component. The below code describes how props are accessed inside the functional component (‘display.js’).
Javascript
// App.js import React from "react" ; import Display from "./components/display" ; function App() { return ( <div> <Display greetings= "Welcome" brandName= "w3wiki" /> </div> ); } export default App; |
Javascript
// display.js import React from "react" ; // Here, texts are passed as a props to this component. function Display(props) { return ( <div> <h1> Hello all, {props.greetings} to {props.brandName}! </h1> { /* Changed from the above example by adding 'Hello all' instead of 'Hello' */ } </div> ); } export default Display; |
Output: The output of the above mentioned code is as follows:
How to access props inside a functional component?
React is an open-source JavaScript library that is mainly used for developing User Interface or UI components. It is a single-page application that is popularly used for developing dynamic web interfaces. While building a React application, the React components serve as basic building blocks.
In React, web applications are built by the combination of these components to develop or create complex user interfaces.
Table of Content
- What are props inside a functional component in React?
- How to access props inside functional components?