React is a component-based library for developing user interfaces. We need components because we want to have customizable parts of UI, and that way, we’ll be able to use one component in different places by changing it a little.

How do we customize a component? Well, we use props for it. Think props as function parameters; a component returns a UI using props data.

Let’s make a Popup component that has some props.

Create a React app with create-react-app and create a Popup.js file:

src/Popup.js

import React from 'react'

const Popup = (
    { Title, Text, backgroundColor }
) => {
    return (
        <div
            style={{
                backgroundColor: backgroundColor,
                margin: "1rem",
                width: "20rem",
                padding: "0 1rem 1rem 1rem"
            }}
        >
            <h1>{Title}</h1>
            <div
                style={{
                    marginTop: "1rem",
                }}
            >
                {Text}
            </div>
        </div>
    )
}

export default Popup

As you can see, the Popup component takes three props: Title, Text, backgroundColor and uses the props to return a UI dynamically.

Jump into App.js and modify it like this:

src/App.js

import React from 'react';
import Popup from './Popup';

const App = () => {
  return (
    <div>
      <Popup
        Title="Red Popup"
        Text="This is a red popup. "
        backgroundColor="red"
      />

      <Popup
        Title="Blue Popup"
        Text="This is a blue popup. "
        backgroundColor="blue"
      />
    </div>
  )
}

export default App

And the output is :

Tip: We used the destruction statement in our Popup component to get props, we could also do it like this, and it’ll work exactly the same:

.
..
const Popup = (
    props
) => {
    const Title = props.Title;
    const Text = props.Text;
    const backgroundColor = props.backgroundColor;
..
.

That’s all for this article, I hope you enjoyed and learned a lot.

👋 Hey, I'm Osman Armut
Hi, I'm Osman Armut. I'm a self taught frontend developer that has a great passion for Javascript and React ecosystem. I use articles in my personal learning journey and I like to share my knowledge to help people.

💬 Leave a comment

Your email address will not be published.

We will never share your email with anyone else.