Challenges

React Props

Using Props

It'd be nice, if we can show the user's name when rendering the welcome message. Here's how we can do that:

function Welcome(props) {
    return (
        <div>
            <hr/>
            <p>Hey {props.name}, Welcome to React</p>
        </div>
    )
}

function Page() {
    return (
        <div>
            <h1>Hello World</h1>
            <Welcome name="Arunoda" />
        </div>
    )
}

As you can see, it's pretty straightforward. But, let me clarify some things for you:

We can pass the name into our component like this:

<Welcome name="Arunoda" />

These values are known as props. React pass these props as the first argument of our functional component:

function Welcome(props) {
    console.log("The name is: " + props.name); 
    ...
}

Then we can render these props inside the curly brackets like this:

<p>Hey {props.name}, Welcome to React</p>

In our app, we need to render the name as lowercase always. But when passing the props, it could be like this:

<Welcome name="ARUNODA" />

So, how can we render the name as lowercase always? Here are some solutions:

(Use this React playground to try React)

Solution 1

function Welcome(props) {
    return (
        <div>
            <hr/>
            <p>Hey {props.name.toLowerCase()}, Welcome to React</p>
        </div>
    )
}

Solution 2

function Welcome(props) {
    const name = props.name.toLowerCase()
    return (
        <div>
            <hr/>
            <p>Hey {name}, Welcome to React</p>
        </div>
    )
}

Solution 3

function Welcome(props) {
    return (
        <div>
            <hr/>
            <p>Hey {`${props.name.toLowerCase()}`}, Welcome to React</p>
        </div>
    )
}
Q: Find the correct solution?
authenticating...

🙏 We need your help

We need your help to keep maintain & add new content to this course. Here's how you can support us: