Principles of components: Props

최윤서·2024년 3월 5일

I'm noob to React

목록 보기
2/2

Componets are the reusable blocks of code acts like a JS function.
In JS functions, it is able to pass values as arguments so that it would be more flexible and easier to use.
It is possible in React using props.

Background - JS Object

In JS, object is a variable that can contain many values, and consists of groups of related data of different types.

const fruit = {type:"Apple", colour: "green"};
console.log(fruit.type);

As you see, in object, properties have name-value match.
It is able to acess to the object's properties using dot notion.

In React, you can use the similar technique to pass the data from one componet to another using the properties object or simply props.

React Props

Props allow you to pass data from one component to another.

Props is essentially a javascript object. So, it can accept many data types from int, string to arrays, fucntions ...

With props, it is able to work more flexibly.

You can send the value, title, to be passed to App.js.
So, when App.js is rendered, it takes the value of the props and puts it as a value of h1 tag.

Data flow of props

When two components communicate with each other, the component sending the data is the parent and the reciving one is child. In the case above, index.js is a parent component and App.js would be a child component.

It's possible for the parent component to send the same data to multiple child components. But, it is impossible for the child components to communicate back to the parent components using props.

Limitation

  • It is not able to communicate back to the parent components for child components.
  • Pure functions: a fucntion which always returns the same output for the same argument values.

So, when you decalare a function using props, it must never modify its own props.

fucntion Heading (props) {
	props.title = "new value"; //not allowed
    	retun (
        	<h1>{props.title}</h1>
        );

};
profile
일 잘 하고싶은 기개디자이너

0개의 댓글