For enquiries call:

Phone

+1-469-442-0620

April flash sale-mobile

HomeBlogWeb DevelopmentHow to Use React Props with Source Code [Beginners Guide]

How to Use React Props with Source Code [Beginners Guide]

Published
29th Sep, 2023
Views
view count loader
Read it in
16 Mins
In this article
    How to Use React Props with Source Code [Beginners Guide]

    React is a JavaScript library for building UI. It is declarative, component-based with the Learn Once Write Anywhere paradigm. The imagination works like a Lego-box here where each website can be distributed into components.  But before that, I would suggest you have a prerequisite strong knowledge of web development basics from the best course for web development. 

    Components allow the user interface to split into multiple independent, reusable modules. For say every day we search on google we can divide it into a component-based design like 

    Now, what is the React component or what are props in React JS? If you want to know, keep reading to know more about React props and its use guide! 

    What are the Props in React? 

    Props are one of the ways in React to think about Data Props are like arguments to a function, so when you create any component and want to render it on the go, you are needed to pass data into it to make that component be shown on a web application. For that we need props. 

    Props stand for properties. Props behave the same to components as arguments behave to functions. 

    Props are the arguments that are passed from the parent component to the child component uni-directional with immutable properties such that once assigned, they would never change their value. 

    They are just passed to your React components to re-render the application every time with different states of data and update the DOM. 

    But to increase your skills in React more, you can have a crash go-through best course for Web Development. 

    Why are Props useful?

    Props are an essential way, or you can say the first way to initialize the component you want to render, we need to learn how to use props in React because without the use of props our component just behaves like a Lego box with no information about it in it. Display and manipulation of information are done through props. 

    As React is component-based, props are the objects to pass data from one component to another combining each and every piece of information to end result in a dynamic web application that is component-based under the hood. 

    Props act as a flow of data to make your app dynamic, with every click of the user on the website rendering or re-rendering specific information according to that. Props are your data-carrying people. 

    React Props Syntax 

    It starts with React JSX to render something static or dynamic on the browser. Followed by transforming React application into component distribution. Props come into the picture then to pass the data between components by defining custom HTML attributes with JSX syntax. The syntax can be well displayed in the code given below where HelloCounter is the component that renders the application title to the React parent component using props. 

    The code is shown below: 

    import * as React from "React"; 
    const App = () => { 
        const welcomeMessage = "This is a counter "; 
        return ( 
            <div> 
               <HelloCounter text = {welcomeMessage} /> 
           </div> 
    )} 
    const HelloCounter = (props) =>{ 
        return <h1>{props.text}</h1> 
    }; 

    React Component Props by Example

    Props can be used in both class and functional components.

    The first and basic example works like creating a DisplayDetails component that will render basic information of a thousand students dynamically and rendering data using props. 

    import * as React from "React"; 
    const App = () => { 
        return ( 
           <div> 
            <DisplayDetails  name = {"Sakshi"}  age={"24"} city ={"delhi"} 
             course ={" React Props"}  /> 
      </div> 
    )}; 
    const DisplayDetails = (props)=>{ 
      return ( 
          <div> 
                <h1> user details </h1> 
                      <ul> Name : {props.name} </ul> 
                      <ul> City : {props.city} </ul> 
                      <ul> Age : {props.age } </ul> 
                      <ul> Course : {props.course} </ul> 
         </div> 
    )}; 
    export default App; 

    1. Multiple props

    Passing multiple props to the components results in destructuring of props.

    This profile card can be used as a use-case to pass as props to render profile cards.  

    2. Class component props

    Class components are the other way to pass props or be the object medium to pass data between components. 

    The class component can be explained with an example where the background of the component can be changed with the click of a button. So background changing needs color data which needs to be passed as props to be dynamic on render. 

    Often functional components are used now to render components but legacy codes and other application requirements do sometimes need the use-case of class components.

    Class components have a concept to use called states where states are only accessible via the creation of props in class components. 

    import * as React from "React"; 
     class Name extends React.Component { 
        render() { 
           return <h1> Hello ! {this.props.name} </h1> 
        } 
    } 
     function App() 
    { 
        return <Name name="React" />; 
    } 
     
    export default App;

    Check out the best React online course to kickstart your React journey. 

    Using React Props 

    The theory we simulated till now gives us enough glimpse of how and what of props. How component-based React is the core of web applications, components use props and act as fundamentals of puzzle pieces. 

    Props can store arrays, values, and functions and their functionality enhances the working of components only.  

    The REACT props example can be illustrated with the use-case of : 

    1. Using a Prop in the Header Component

    The Header component is the functional component needed to be rendered as a puzzle piece of the web application shown in the browser. It takes prop alias to data attribute as an argument to the component to make it accessible to the parent component i.e. App.js where Header is the child component.

    export default function Header(props) { 
        console.log(props) 
        return ( 
           <div> 
                 <h1>{props.heading}</h1> 
           </div> 
    ); 
    }

    2. The App.js File

    This is the header component rendering the data using props on the browser. But the data cannot be shown until the header component is passed into the parent App.js component to render it.

    import Header from "./components/Header"; 
    function App() { 
       return ( 
          <div> 
              <Header heading ="React props Guide " /> 
         </div> 
       ); 
    } 
    export default App;

    This is how props work with respect to Header and App.js file, And this is how data is passed through props from parent to child rendering the Header component specifically. 

    But we should also see one more thing console.log(props) will output an object consisting of props.heading value. 

    Using Default Props

    We know that React components take props as input in the form of arguments and parent components pass it down to child components making different child components render together on a web application completing a full UI widget. 

    When the parent component cannot pass any prop to the child component, it becomes a problem for the child component to determine what to render. 

    For example, if there is a Header component but the main component App.js do not pass any prop(data) to the Header component resulting screen remains blank. 

    1. The Updated App.js File

    The updated App.js file renders like this: 

    import Header from "./components/Header"; 
    function App() { 
       return ( 
          <div> 
              <Header/> 
         </div> 
       ); 
    } 
    export default App; 

    This very undefined render of the component seems like our app is breaking. But we know it is not. Then what is the solution? 

    So the solution is to have a safe fallback value for the prop if something goes missing on the side of the parent component while passing the prop, the child component would not remain empty-handed, it would have a fallback or default value to rely upon. 

    2. Using Default Props Example for React set props

    export default function Header(props) { 
       console.log(props); 
       return ( 
         <div>. 
              <h1> {props.heading || "Default heading" } </h1> 
         </div> 
    ); 
    } 

    This works fine for very little informative component rendering, attaching | | ( OR ) operator to the props. The systematic and correct way to pass the fallback value is defaultprops. 

    defaultProps is one of the prop static properties to set a default value for the prop argument passing from parent to child component. 

    Header.defaultProps ={ 
       heading :" Learning about React Prop" 
    } 

    Prerequisites

    As props are the means of passing data between components where data flow is unidirectional from parent component to child component. But states and understanding how React actually works under the hood is important. 

    React basically maintains a tree for you which your browser treats like a DOM and when you start to React app with

    ReactDOM.render( <App/> , container )

    React simply constructs a tree if UI with lazy reconciliation making the least of the changes possible after re-render. Components we write are not understandable by the browser; a Babel compiler is needed to convert code into browser-understandable code whereas Bable executes every JSX into React.createElement( type, [props], [....children]) which is then converted into an object representation. 

    The second prerequisite to understanding is the difference between state and props. Props, we know are the arguments to the components for displaying something to the user: we can have title or subtitle as props, but the state is handled inside the component. For example, the current value of count in counter problems is inside the state. Re-render of state changes the application, but props are immutable.

    How to Use React Props with Source Code [Step-by-Step] 

    In React, props are used to display and pass data that is immutable to render data, but re-rendering the component requires updating the state as we discussed earlier. 

    This looks a little ambiguous right? But JSX is a powerful tool used by props to display dynamic components. Before moving into steps, we need to have a look at the destructuring property of props. 

    How to use props without destructuring in React functional component props:

    export default function Header(props) { 
       console.log(props) 
       return ( 
          <div> 
             <h1> {props.title} </h1> 
         </div> 
    ); 
    } 

    This code creates a simple Header component taking props as arguments inside <div> tag. Inside the <div> tag there is a prop object called title which has not yet passed any data to render on the browser. The prop here is not destructured so when you console.log it outputs an array of objects where key value can be accessed using the dot operator for say props.title.

    Now the step-case for using React-prop is 

    Step 1: Pass in props as an argument

    This allows you to pass prop as the argument. React props have no limitation as React allow to pass function as a prop too which is altogether in the same way you do to arguments. 

    export default function Header(props) { 
    } 

    Step 2: Declare props variable(s)

    export default function Header(props) { 
      const title = props.name; 
    } 

    Step 3: Use variable(s) in JSX template

    export default function Header(props) { 
      const title = props.name; 
      return ( 
        <div> 
           <h1>Prop Learning Steps</h1> 
           <h2>Title : {title} </h2> 
         </div> 
    ); 
    } 

    Step 4: Pass data to props in the App component

    import Header from "./components/Header"; 
    function App() { 
        return ( 
            <div> 
              <Header name = "React prop Step-4" /> 
           </div> 
    ); 
    } 
    export default App; 

    Step 5: React props also offers to debug or type checking with React proptypes

    Proptypes or React proptypes is the third-party package that allows one step extra debugging for type-safe check. It allows us to fix and find bugs with ease. 

    It allows you to check and compare the equivalence of types used for rendering with the data passed in the props. 

    Eg: If age is the prop in the component, it should have a type number only, not the string. Proptypes make sure of that. 

    React TypeScript props can also be used for type-checking but the overload of its overhead in the small-scale applications is quite inefficient.

    npm install -- save prop-types 
    import PropTypes from "prop-types" 
    export default function DisplayBasicINFO({ name , age }) 
    { 
      return ` I am {name } will be {age +1} years old after 1 year ` 
    } 
    DisplayBasicINFO.propTypes={ 
    name : PropTypes.string , 
    age : PropTypes.number 
    }

    How to Use Props with Destructuring

    Sometimes when a prop is an object, it is better advised to destructure in the child component before using it to display data from that component. In large-scale apps where a lot of data is needed to pass down, destructuring makes the code more concise and readable. 

    Destructuring requires the extraction of elements from an array or object by assigning them to their own variable. 

    Suppose we have an object called studentInfo in React function props to pass down to DisplayInfo component.

    const studentInfo = { 
        firstName : "Sakshi", 
        lastName : "Jain", 
        city : "Delhi", 
        course : "React props" 
    } 

    Now we can destructure React props in the Display component to make it more easily accessible.

    export default function Display (props) 
    { 
       const firstName = props.info.firstName; 
       const lastName = props.info.LastName ; 
       const city = props.info.city; 
      const course = props.info.city; 
      return ( 
         <div>.    
             <h1> Student Page </h1> 
             <h2> Name : { firstName}{" "}{lastName}</h2> 
             <h2>city : {city} </h2> 
        </div> 
    ); 
    }

    How to Set Default Values For Props

    Default prop is used when no data is passed between components, and it is rendered without any display of data on the browser somehow. 

    The one way to set the default prop is destructuring the object as follows:

    studentInfo.defaultProps = { 
       firstName : " Test ", 
       lastName :  " Data " 
    } 

    Default props always make the programmer sure of some values are always set up for the props to pass between components to avoid blank white pages with no data rendered. 

    React Props Pitfalls

    React is the most trendy and popular front-end framework and does have certain error boundaries to be taken care of after understanding the fundamentals well. 

    1. Do create enough components for every feature, React is component-sized and it works well when each component only contributes to one function in the application, and together they complete the puzzle with efficiency. 
    2. React Props are immutable it is hard to digest, but they are not changeable and very likely to be compared with states. Remember state and props in React have a very thin line difference. 
    3. Passing good type comparison to the props while delegating data is important. 
    4. DOM element should not roam around with unwanted props in its hand. Props must be positioned and passed systematically to avoid Unknown Prop Warning. 
    5. Passing the prop correctly to the correct component is vital. 

    Can We Use Props and State Together?

    Props and state do may seem poles apart, but they work hand in hand to make the component render dynamically. The state of components does become the prop to pass to the child component. State stores the current data your page needs to render with but props delegate data and events to the child component. 

    States work like local variables of functions that remain inside the local scope of a component only to do its work and then change. But props make the component reusable with tons of data replacing every time for rendering of repeated information from the same component every time differently without any redundancy. 

    A component can and cannot have the component but manages its own state internally. They do work together but guard their own roles in the process of rendering components. 

    Unleash your coding potential with our beginner Python course. Learn the language that powers tech giants and start your journey towards becoming a programming pro. Join us today and unlock a world of endless possibilities.

    What are the Differences Between Props and State?

    Let’s take a look at some high-level differences between state and props. Although they do similar things, they are used differently.   

    While both are used for data manipulation, one is private, and the other is of dynamic context.      

    • Props are used to pass data from parent to child whereas the state is used for data manipulation inside the component. 
    • We can get the value of props from the parent component, where we get the value of the state object from the initial data defined in the constructor() method. 
    • While this.props is set up by React itself, with this.the state we are free to manually add additional fields to the component to store something or in a scenario that doesn’t participate in the data flow.  
    • Props are immutable, i.e. We can't change props passed to a component whereas we can change the State, i.e React uses the setState() method to update the object of a state (but within the component itself) 

    Later the fundamentals of yours I would suggest can be excelled with this best React online course KnowledgeHut. 

    Conclusion

    This was all about React Props, the very basic way to start with React application and the power of React props, its usage and properties show the dynamic and flexible nature of React applications well and efficiently. 

    Frequently Asked Questions (FAQs)

    1. Why do we use render props in React?

    Render props helps in sharing code between the components. They mostly serve high-order components to extract out common functionalities keeping your code DRY. 

    2. Can I pass JSX as a prop?

    You can simply pass JSX as a prop using  { } curl braces to parse the data, but JSX element must return only one root element then. 

    3. Are props read-only?

    Props have a very important property of read-only feature due to their immutable nature, you cannot change or update it unless you again pass updated props explicitly back to the child component. 

    4. How many props should a component have?

    In general, there is no such rule of number in sending props to components, but there is something called best practices for writing good code. The minimum no of parameters or props is more readable and else it depends on the requirement of the component and what exactly it needs to render. Just remember do not overweight your component. 

    Profile

    Sakshi Jain

    Author

    I’m Sakshi, a passionate Web Developer who is keen on learning. Coding empowers magic to my thought with the wing of programming where that thought likes to write around Web Development and programming languages domain.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon