DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Shoko Kimera
Shoko Kimera

Posted on

Simplest Way to create and pass props in React

Create a prop

Lets say there are two components, a Parent and Child function component as seen below. Here how we can pass data from the Parent to the Child.

function Parent() {

    return (
        <>

        </>
    )
}
export default Parent;
Enter fullscreen mode Exit fullscreen mode
function Child() {

    return (
        <>

        </>
    )
}
export default Child;
Enter fullscreen mode Exit fullscreen mode

Step 1

create a Parent component state using the useState React hook.

import { useState } from 'react'

function Parent() {
    const [word, setWord] = useState()

    return (
        <>

        </>
    )
}
export default Parent;
Enter fullscreen mode Exit fullscreen mode

Step 2

Return the Child component in the parent component

import { useState } from 'react'
import Child from './Components/Child'

function Parent() {
    const [word, setWord] = useState()

    return (
        <>
            <Child />
        </>
    )
}
export default Parent;
Enter fullscreen mode Exit fullscreen mode

Step 3

We pass the props in the Child component as an argument (similar to how we do it in a regular function). We must use curly braces { } to access data defined in JavaScript and pass it as the props for Child component, In this case we pass the word state.

import { useState } from 'react'
import Child from './Components/Child'

function Parent() {
    const [word, setWord] = useState()

    return (
        <>
            <Child theWord = { word } />
        </>
    )
}
export default Parent;
Enter fullscreen mode Exit fullscreen mode

Step 4

Now here’s how we utilize the passed props data in the Child component, using the curly braced { } is important for passing props without using the props object (which we’ll see later on).

function Child({ theWord }) {
    console.log(theWord)
    return (
        <>
            <p> { theWord } </p>    
        </>
    )
}
export default Child;
Enter fullscreen mode Exit fullscreen mode

Extra

You can also specify a default value for your props, say we wanted the default word (when no value has been passed to word from Parent) to be β€œkakashi” here’s how we do it.

function Child({ theWord = "kakashi" }) {
    console.log(theWord)
    return (
        <>
            <p> { theWord } </p>    
        </>
    )
}
export default Child;
Enter fullscreen mode Exit fullscreen mode

But if you pass theWord={null} or theWord={0}, the default value will not be used

Top comments (0)

Why You Need to Study Javascript Fundamentals

>> Check out this classic DEV post <<