
2. Props
React Fundamentals: Props
Introduction to React and Components
React is a popular JavaScript library for building user interfaces, mostly for single-page applications. It allows developers to create large web applications which can change data, without reloading the page.
The heart of React lies in components. Components are independent and reusable bits of code that serve as the building blocks of a React application's UI. They are like functions that return HTML elements.
What are Props?
Props, short for properties, are how components talk to each other. They are arguments passed into React components which allows you to pass data from one component to another, as parameters.
In React, data flows unidirectionally (from parent to child components) via props.
Setting Up a React Project
To start a new React project, follow the following steps:
- First install the
create-react-app
package globally in your system using the following command:
npm install -g create-react-app
- Next, create a new React app using the following command:
npx create-react-app PROJECT-NAME
- Navigate into your newly created project folder:
cd PROJECT-NAME
- To start the development server, execute the following command:
npm start
Styling in React
In React, there are several ways to style your components. One of them is Inline Styling.
Inline styles are written as JavaScript objects, where properties are written in camelCase.
Here's an example:
import React from "react";
const person = {
name: "Ayxan",
age: 24,
theme: {
backgroundColor: "deepskyblue",
color: "white"
}
}
function getFullInfo() {
return "NAME : " + person.name + " AGE :" + person.age;
}
export default function Item() {
return (
<div>
<h1 style={person.theme}>My name is {person.name}</h1>
<h2>I am {person.age} years old</h2>
<span>{getFullInfo()}</span>
</div>
);
}
Props in Action
Props are the way components can read values from their parent components.
Here's an example:
// ParentComponent.js
import React from "react";
import ChildComponent from "./ChildComponent";
const ParentComponent = () => {
return (
<ChildComponent myinfo="Ayxan" />
);
};
export default ParentComponent;
// ChildComponent.js
import React from "react";
const ChildComponent = (props) => {
return (
<div>
{props.myinfo}
</div>
);
};
export default ChildComponent;
In this example, the ParentComponent is passing a prop myinfo
to the ChildComponent. Inside the ChildComponent, we access this prop using {props.myinfo}
.
Reference
The content in this document is based on the original notes provided in Azerbaijani. For further details, you can refer to the original document using the following link:
Original Note - Azerbaijani Version