October 9

Passing Props in React

0  comments

Do you also love working with React? If yes then you have surely heard of the term props. If not well its not as complicated as it sounds. Let me show you how to use it properly 😉 

Requirements to follow along: 

  • Be able to install React with create-react-app
  • Understand How to work with React constructor -- not using hooks in this simple guide. 

What are props?

Props in React is just data that we pass among components to share information that could be useful in the component that we pass it to.

When working with React you are going to pass around props all the time and you will see just how useful it can be.

Let me demonstrate..

Before we begin I would suggest that you code along if you want the information to stick, also go ahead and just copy the CSS below into your app.css file.

.App {

  text-align: center;

}

form{

  border: 1px solid black;

  width: 30%;

  margin: 0 auto;

  padding: 1rem;

}

input{

  margin: 0.5rem;

}

button{

  display: block;

  margin: 0 auto;

}

label{

  display: block;

}

Firstly lets create a Introduction component where we introduce our user. Notice the "props.name" and "props.age" below. 

import React from 'react'


function Introduction(props) {

    return <p> Hello my name is {props.name} and I am {props.age} years old!</p>

}


export default Introduction

Props still need to be passed to this Component from our parent Component so lets do that. Inside our App.js file below we are going to import our Component  "Introduction" which is a functional component. We use a functional component here because we do not need to store state inside this component. 

Now where are the props we were talking about? In our App.js file where we bring in our Introduction component you will see there is a name and an age. These are two props that we pass down from component to component just like explained above.


import React from 'react';

import './App.css';

import Introduction from './components/Introduction/Introduction'


function App() {

  return (

    <div className="App">

      <h1>Passing Props</h1>

      <Introduction name='Phil' age='22' />

    </div>

  );

}

export default App;

So that was very simple, but maybe we should allow the user to fill in their name and age by themselves. Time to create a form so the user can give us their details. In this case we are going to use a class Component, because we need to store the data from the user in state.  Lets make a function called "handleChange" inside both input fields so we can change the state when a user enters their age and name. 

import './form.css';


class Form extends Component {

    constructor(props) {

        super(props)

        this.state = {

            name: '',

            age: '',

        }

        this.handleChange = this.handleChange.bind(this)

    }

    handleChange(event) {

        const type = event.target.name;

        const value = event.target.value;

        this.setState({

            [type]: value

        })

    }

    render() {

        return (

            <div>

                <form action="submit">

                   <label>What is your name?</label>

                   <input

                    type='text'  

                    name='name'

                    onChange= {this.handleChange} 

                   type="text"

                     />

                    <label>How old are you?</label>

                    <input

                     type='number'

                     name='age'

                     onChange={this.handleChange}

                    type="text"

                      />

                    <button type='submit' >Submit</button>

                </form>

            </div>

        );

    }

}

export default Form;

So now we got our form all set up, time to bring it into our App.js below. We want to pass our state from the user into our Introduction Component, but we are going to run to a problem here. It is not possible to get our state of "age" and "name" from our Form component into our App Component in order to pass it down to our Introduction Component. 

Why? Form is a child of our App Component and *Props can not be passed from child to Parent Components* This can be done with Redux or React Context API, but that is beyond the scope of this guide. 

So lets import Form and remove our Introduction Component here. 

import React from 'react';

import './App.css';

import Form from './components/Form/Form'


function App() {

  return (

    <div className="App">

      <h1>Passing Props</h1>

      <Form />

      <Introduction name='Phil' age='22' />

    </div>

  );

}

export default App;

We are going to add our Introduction Component inside our Form component below in order to pass our state down as props. Now state gets passed directly to our Introduction Component. You will notice that when entering data into our form that it changes the output of Introduction. So whatever you type into name and and age in the form will now get displayed. 


                 <form action="submit">

                    <label>What is your name?</label>

                    <input type='text'  

                      name='name'

                      onChange={this.handleChange}

                      type="text"

                       />

                    <label>How old are you?</label>

                    <input type='number'

                      name='age'

                      onChange={this.handleChange}

                      type="text"

                       />

                    <button type='submit' >Submit</button>

                </form>

                <Introduction name={this.state.name} age={this.state.age} />

            </div>

And that is basically all there is to passing props from component to component! We can however make some improvements to our code. Lets start by updating our Form Component so the "name" and "age" only updates when submitting the form and if nothing is submitted we want to display a different message. 

Below we add "formData" into our state which is going to be our new props that we pass to the Introduction Component.

We add a "handleSubmit" function that takes the users input and updates the "formData" state once the user clicks on submit. 

Notice in our input tags a "pattern" property is added. This is a nice little trick to prevent a user from entering the wrong data when submitting a form. 

Our Introduction should now only update when pressing the submit button.


import React, { Component } from "react";

import './form.css';

import Intro from '../Introduction/Introduction';

class Form extends Component {

    constructor(props) {

        super(props)

        this.state = {

            name: '',

            age: '',

            formData: {

                name: '',

                age: ''

            }

        }

        this.handleChange = this.handleChange.bind(this)

        this.handleSubmit = this.handleSubmit.bind(this)

    }

    handleChange(event) {

        const type = event.target.name;

        const value = event.target.value;

        this.setState({

            [type]: value

        })

    }

    handleSubmit(event) {

        event.preventDefault()

        let name = this.state.name;

        let age = this.state.age;

        this.setState({

            formData: {

                name: name,

                age: age

            }

        })

    }

    render() {

        return (

            <div>

                <form action="submit" onSubmit={this.handleSubmit}>

                    <label>What is your name?</label>

                    <input 

                     type='text'

                     pattern="[a-zA-Z]*"

                     name='name'

                     onChange={this.handleChange}

                      />

                    <label>How old are you?</label>

                    <input 

                     type='number'

                     pattern="[0-9]*" 

                     name='age'

                     onChange={this.handleChange}

                      />

                    <button type='submit' >Submit</button>

                </form>

                <Introduction

                name={this.state.formData.name}

                age={this.state.formData.age}/>

           </div>

        );

    }

}

export default Form;

Finally lets make one small change to our Introduction Component so when no data has been entered into the form we get a different message. 

Add in the while loop below to add that functionality. 

import React from 'react'

function Introduction(props) {

    while (props.name == ''" || props.age == ''") {

        return <h1>Fill out the form to see result</h1>

    }

    return <h1> Hello my name is {props.name} and I am {props.age} years old!</h1>

}

export default Introduction


Tags


You may also like

Passing Props in React

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

Subscribe to Receive the Latest Updates

>