How to pass numbers as Props to a Component in React

To pass data between components, we often use the prop. Passing numbers as Props to a Component in React is the same thing. In this article, we will use the syntax {} of JSX to do that.

Passing numbers as Props to a Component in React

Using JSX ‘{}’ syntax in class component

In the App component, we will create a string like this:

import React, { Component } from "react";

class App extends Component {
    render() {
        return <div>I'm 24 years old</div>;
    }
}

export default App;

Output:

I'm 24 years old

Now go to the index.js file to add props to the component:

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App";

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
  <StrictMode>
    <App age = {24} />
  </StrictMode>
);

The root is a ReactDom object (testable by console.log variable root ).

The root variable calls the render method (function), and this function takes as an argument a piece of JSX code, which we see inside the structure containing the <App/> markup. Right next to the call to the App component, type any property name and assign it a value. Here we will set the value ‘age’ to 24.

Continue to open the file App.js.

We will call the props named ‘age’ from the class using ‘this’ wrapped in JSX syntax.

import React, { Component } from "react";

class App extends Component {
    render() {
        return <div>I'm {this.props.age} years old</div>;
    }
}

export default App;

Output:

I'm 24 years old

Using JSX ‘{}’ syntax in the function component

In a function component, the components receive the same props as a regular function argument. A function component will receive an object with the properties you described in the component called:

import React from "react";

function App() {
    return <Person name="Anna" age={27} />;
}

function Person(props) {
    return (
        <p>
            My name is {props.name}. I'm {props.age} years old
        </p>
    );
}

export default App;

In the example above, the Person component contains a <p> tag that displays a person’s name and age through a representation prop. It is very useful when we need to transfer a lot of data at once.

Please note that for numeric values, enclose it in {} syntax, and for string types, you only need to enclose the value in double quotes.

Output: 

My name is Anna. I'm 27 years old

Summary

In conclusion, you can Pass numbers as Props to a Component in React into props using the special {} syntax in JSX. This is how props allow you to send data using a top-down approach, where a component at a higher level can send data to a component below it.

Leave a Reply

Your email address will not be published. Required fields are marked *