惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Securelist
C
CERT Recently Published Vulnerability Notes
Forbes - Security
Forbes - Security
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
L
LINUX DO - 最新话题
The Hacker News
The Hacker News
Google Online Security Blog
Google Online Security Blog
SecWiki News
SecWiki News
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
The Last Watchdog
The Last Watchdog
S
Schneier on Security
T
Troy Hunt's Blog
N
News | PayPal Newsroom
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Schneier on Security
Schneier on Security
P
Privacy & Cybersecurity Law Blog
T
Tor Project blog
T
Threatpost
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
A
Arctic Wolf
S
Secure Thoughts
P
Proofpoint News Feed
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Security Latest
Security Latest
Scott Helme
Scott Helme
Security Archives - TechRepublic
Security Archives - TechRepublic
Latest news
Latest news
PCI Perspectives
PCI Perspectives
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Hacker News - Newest:
Hacker News - Newest: "LLM"
L
LINUX DO - 热门话题
P
Palo Alto Networks Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
G
GRAHAM CLULEY
V2EX - 技术
V2EX - 技术
Google DeepMind News
Google DeepMind News
Project Zero
Project Zero
V
Vulnerabilities – Threatpost
T
Threat Research - Cisco Blogs
Webroot Blog
Webroot Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
N
News and Events Feed by Topic
TaoSecurity Blog
TaoSecurity Blog
大猫的无限游戏
大猫的无限游戏
T
Tenable Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
V
Visual Studio Blog
H
Hacker News: Front Page
Simon Willison's Weblog
Simon Willison's Weblog
AWS News Blog
AWS News Blog

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
A Simple Guide to Component Props in React
Dmitri Pavlutin · 2021-07-02 · via Dmitri Pavlutin Blog

To start using React you don't have to learn a lot. Learn the concept of components, state, props, and hooks — and you know how to use React.

In this post, you'll read a simple but pragmatic guide on how to use props on React components.

1. The component props

A component is an encpasulated piece of logic. For example, here's a component that displays a Hello, World! message:


function HelloWorld() {

return <span>Hello, World!</span>;

}



// Render

<HelloWorld />

// Output

<span>Hello, World!</span>


The problem with <HelloWorld /> component is that it is inflexible. You cannot change the greet person , e.g. use Joker instead of Earth.

You can solve this issue by using the concept of component props.

Let's make the <HelloWorld /> component more flexible by adding a prop who. The who allows to custimize the person that's being greeted. Let's name the new component <Hello>.

There are 2 steps to add the who prop to <Message> component:

1) Make the function of your component read the props from the props parameter:


function Hello(props) {

return <div>Hello, {props.who}!</div>;

}


Now Hello function has a parameter props. When rendering the component, React will make sure to assign to props object all the props you assign to the component.

2) When rendering the component, add the prop to the component using the attribute-like syntax who="Earth":


// Render

<Hello who="Earth" />

// Output

<div>Hello, Earth!</div>


You can use any who prop value you'd like. For example, let's greet the Mars!


// Render

<Hello who="Mars" />

// Output

<div>Hello, Mars!</div>


That's all you need to know in order to use React props!

1.1 Multiple props

Of course, you can use as many props as you like. Let's make the <Message> component accept 2 props to customize the greet message, as well as the greet person:


function Message({ greet, who }) {

return <div>{greet}, {who}!</div>;

}



// Render

<Message greet="Welcome" who="Aliens" />

// Output

<div>Welcome, Aliens!</div>


1.2 Class component props

If you use class-based components, then you can access the props from this.props property of the component instance.


import { Component } from 'react';

class HelloAsClass extends Component {

render() {

return <div>Hello, {this.props.who}!</div>;

}

}


Setting the prop value for a class component is the same as for a functional one:


// Render

<HelloAsClass who="Earth" />

// Output

<div>Hello, Earth!</div>


2. Values of props

In most of the previous examples, the values of props were strings. But often you'd like to set props to values like numbers, booleans, objects, arrays, and even variables.

React doesn't put any restriction on what value a prop can have. But all values, except double-quoted string literals, have to be wrapped in curly braces prop={value}.

Use the following guide to set different types of values on your components.

  1. String literals:


<MyComponent prop="My String Value">


  1. Template literals with variables:


<MyComponent prop={`My String Value ${myVariable}`}>


  1. Number literals:


<MyComponent prop={42} />


  1. Boolean literals:


<MyComponent prop={false} />


  1. Plain object literals:


<MyComponent prop={{ property: 'Value' }} />


  1. Array literals:


<MyComponent prop={['Item 1', 'Item 2']} />


  1. JSX:


<MyComponent prop={<Message who="Joker" />} />


  1. Variables having any kind of value:


<MyComponent prop={myVariable} />


3. Passing down props

Inside the component you can use props as any regular JavaScript variable. You can render conditionally, or you even pass down props to other components.

For example, let's create a component <HelloPeople /> that accepts a list of persons. This component is going to pass down each person to the <Hello> component.


function HelloPeople({ persons }) {

return (

<div>

{persons.map((person, index) => {

return <Hello who={person} key={index} />;

})}

</div>

);

}


<HelloPeople persons={persons} /> accepts a prop persons — that is an array of string. Inside the component, the list of persons is iterated and each person is mapped to the <Hello who={person} /> component. This way, the props can be passed down to child components.


// Render

<HelloPeople persons={['Joker', 'Batman']} />

// Output

<div>

<div>Hello, Joker!</div>

<div>Hello, Batman!</div>

</div>


4. Optional props

There are situations when you have a good default value for a prop. In such a case, you can omit the prop at all.

However, make sure to indicate the default value when accessing the prop inside of the component.

For example, let's make the who prop inside the <HelloOptional /> component optional, but default to 'Unknown'.


function HelloOptional({ who = 'Unknown' }) {

return <div>Hello, {who}!</div>;

}


Looking at the parameter destructuring { who = 'Unknown' } you would notice that if who prop is not indicated, then it defaults to 'Unknown' value. Great!


// Render

<HelloOptional />

// Output

<div>Hello, Unknown!</div>


However, if indicated, who accepts the actual value:


// Render

<HelloOptional who="Batman" />

// Output

<div>Hello, Batman!</div>


5. Props spread syntax

If you dynamically construct the props of a component, you might hold the props of the component inside of a plain JavaScript object.

For example, let's define the object hiBatman with the properties greet and who:


const hiBatman = { greet: 'Hi', who: 'Batman' };

function Message({ greet, who }) {

return <div>{greet}, {who}!</div>;

}


Then, when setting up the props of the component, instead of manually enumerating the props:


// Render

<Message greet={hiBatman.greet} who={hiBatman.who} />

// Output

<div>Hi, Batman!</div>


you can simply use the spread syntax <Message {...hiBatman} />:


// Render

<Message {...hiBatman} />

// Output

<div>Hi, Batman!</div>


The property names inside of the spread object have to correspond to the prop names.

6. Special props

While you are free to use any prop names you like, React, however, has some properties with special use.

6.1 children

children is a special property assigned by React with the content of the body of the component: the content between open tag <MyComponent> and closing tag </MyComponent>.


function Parent({ children }) {

console.log(children); // logs <span>I'm a child!</span>

return <div>{children}</div>;

}



// Render

<Parent>

<span>I'm a child!</span>

</Parent>

// Output

<div><span>I'm a child!</span></div>


6.2 key

If you recall the <HelloPeople persons={persons} /> component:


function HelloPeople({ persons }) {

return (

<div>

{persons.map((person, index) => {

return <Hello who={person} key={index} />;

})}

</div>

);

}


<Hello who={person} key={index} /> uses the special key prop. It allows React to perform updates on array items faster.

7. Conclusion

Props are a way you can write reusable pieces of UI logic. Props serve as an input for the component.

Using props is pretty simple.

First, make sure your component reads the props from the props parameter (or this.props in case of class components):


function MyComponent({ prop }) {

return <div>Prop value: {prop}</div>;

}


Then, when rendering the component in JSX make sure to set the prop value using an attribute-like syntax: prop="My Value":


// Render

<MyComponent prop="My Value" />

// Output

<div>Prop value: My Value</div>


Next I recommend to take take a look on how React updates the state of components.