-
Your first component¶
-
what is component- React applications are built from isolated pieces of UI called components.Components can be as small as a button, or as large as an entire page
- Each React component is a JavaScript function that may contain some markup,CSS, that React renders into the browser. and which can be reusable
- React components are regular JavaScript functions, but their names must start with a
capital letteror they won’t work! single line return->no need of pair of parentheses , if in multiline pair of parentheses is missed then only first line will be considered rest will be ignored<section> tagis lowercase, so React knows we refer to an HTML tag.<Profile /> componentstarts with a capital P, so React knows that we want to use our component called Profile.
-
Importing and exporting components¶
- The
export defaultprefix is a standard JavaScript syntax (not specific to React). It lets you mark the main function in a file - A file can only have one default export, but it can have numerous named exports!
- importing
default import-> import Gallery from './Gallery.js'; - importning
named import-> `import {Gallery} from './Gallery.js'; - Either ./Gallery.js' or './Gallery'` will work with React, though the former is closer to how native ES Modules work.
- When you write a
default import, you can put any name you want after import. For example, you could write import Banana from './Button.js' instead and it would still provide you with the same default export. - In contrast, with
named imports, the name has to match on both sides. That’s why they are called named imports! Root file- root component file, named App.js in this example. Depending on your setup, your root component could be in another file, though. If you use a framework with file-based routing, such as Next.js, your root component will be different for every page.
- The
-
Writing markup with JSX¶
- JSX is syntax extension for javascript which lets you write HTML-like markup inside a JavaScript file
- Although there are other ways to write components, most React developers prefer the JSX,
- as the Web became more interactive, logic increasingly determined content. JavaScript was in charge of the HTML! This is
why in React, rendering logic and markup live together in the same place—components. - JSX looks a lot like HTML, but it is a bit
stricterand can display dynamic information. - JSX is a syntax extension, while React is a JavaScript library.
- The Rules of JSX
Return a single root element- To return multiple elements from a component, wrap them with a single parent tag.- If you don’t want to add an extra
to your markup, you can write <> and </>instead: - This empty tag is called a
React Fragment. Fragments let you group things without leaving any trace in the browser HTML tree.
- If you don’t want to add an extra
Close all the tagscamelCase all most of the things!- JSX turns into JavaScript and attributes written in JSX become keys of JavaScript objects
- their names can’t contain dashes or be reserved words like class.
-
JavaScript in JSX with curly braces¶
- JSX is a special way of writing JavaScript. That means it’s possible to use JavaScript inside it with curly braces { }
- In addition to
strings, numbers, and other JavaScript expressions,objects can be passed in JSX. - Objects are also denoted with curly braces, like { name: "Hedy Lamarr", inventions: 5 }. Therefore, to pass a JS object in JSX, you must wrap the object in another pair of curly braces:
person={{ name: "Hedy Lamarr", inventions: 5 }} - when you need an inline style, you pass an object to the style attribute
-
Passing props to a component¶
https://codesandbox.io/s/jrycgd?file=/App.js:360-367&utm_medium=sandpack
- Props are the information that you pass to a JSX tag / Component
- React components use props to communicate with each other. communication with parent component -> child components by giving them props.
- you can pass any JavaScript value through them, including objects, arrays, and functions.
- The props you can pass to an
tag / HTML tags are predefined (ReactDOM conforms to the HTML standard). But you can pass any props to your own components,
//passing props <Avatar person={{ name: 'Lin Lanying', imageId: '1bX5QH6' }} size={100} /> // reading props // // this is using props destructuring function Avatar({ person, size = 100 }) { // Specifying a default value for a prop // person and size are available here } or function Avatar(props) { let person = props.person; let size = props.size; // ... } // Usually you don’t need the whole props object itself, so you destructure it into individual props.- Specifying a default value for a prop -> The default value is only used if the prop is missing or if you pass
size={undefined}. But if you passsize={null} or size={0}, the default value will not be used. Passing JSX as children
<Card> <Avatar /> </Card> function Card({ children }) { return ( <div className="card"> {children} </div> ); }props are immutable—meaning “unchangeable”.- When a component needs to change its props (for example, in response to a user interaction or new data), it will have to “ask” its parent component to pass it different props—a new object! Its old props will then be cast aside, and eventually the JavaScript engine will reclaim the memory taken by them.
Props are read-only snapshotsin time: every render receives a new version of props.You can’t change props. When you need interactivity, you’ll need to set state.- You can
forward all propswithJSX spread syntax, but don’t overuse it!
-
Conditional rendering¶
- if statements, &&, and ? : operators.
-
if-function Item({ name, isPacked }) { if (isPacked) { return <li className="item">{name} ✔</li>; } return <li className="item">{name}</li>; } -- use Item in another component(ternary) operator (? :)return ( <li className="item"> {isPacked ? name + ' ✔' : name} </li> ); -
Logical AND operator (&&)- when you want to render some JSX when the condition is true, or render nothing otherwise.
- React considers false as a “hole” in the JSX tree, just like null or undefined, and doesn’t render anything in its place.
Don’t put numbers (0 ) on the left side of &&.- if the left side is 0, then the whole expression gets that value (0), and React will happily render 0 rather than nothing. it should be
messageCount > 0 && <p>New messages</p>.
Conditionally returning nothing with null- In some situations, you won’t want to render anything at all.
if (isPacked) { return null; } return <li className="item">{name}</li>;
- In some situations, you won’t want to render anything at all.
-
Rendering lists¶
export default function List() { const listItems = people.map(person => <li>{person}</li> ); return <ul>{listItems}</ul>; }
-
Keys tell React which array item each component corresponds to, so that it can match them up later.
- This becomes important if your array items can move (e.g. due to sorting), get inserted, or get deleted.
A well-chosen key helps React idenfity what exactly has happened, and make the correct updates to the DOM tree. - Rather than generating keys on the fly, you should include them in your data
- use an incrementing counter,
crypto.randomUUID()or a package likeuuidwhen creating items. Rules of keys- Keys
must be uniqueamong siblings. However, it’s okay to use the same keys for JSX nodes in different arrays. - Keys
must not changeor that defeats their purpose!Don’t generate them while rendering.
- Keys
-
do not generate keys on the fly, e.g. with key={Math.random()}. This will cause keys to never match up between renders, leading to all your components and DOM being recreated every time. Not only is this slow, but it will also lose any user input inside the list items. Instead, use a stable ID based on the data.
-
Keeping components pure¶
- Rendering can happen at any time, so components should not depend on each others’ rendering sequence.
- React’s rendering process must always be pure. Components should only return their JSX, and not change any objects or variables that existed before rendering—that would make them impure!
what is pure function- It
minds its own business. It does not change any objects or variables that existed before it was called. Same inputs, same output. Given the same inputs, a pure function should always return the same result.
- It
- React is designed around this concept. React assumes that every component you write is a pure function. This means that React components you write must always return the same JSX given the same inputs:
Side Effects: (un)intended consequences- changes—updating the screen, starting an animation, changing the data—are called side effects.They’re things that happen “on the side”, not during rendering.
- You can fix this component by passing a prop instead:- Now your component is pure, as the JSX it returns only depends on the prop.
in React there are three kinds of inputs that you can read while rendering: props, state, and context. You should always treat these inputs as read-only.- When you want to change something in response to user input, you should set state instead of writing to a variable. You should never change pre-existing variables or objects while your component is rendering.
- React offers a
Strict Modein which it calls each component’s function twice during development. By calling the component functions twice, Strict Mode helps find components that break these rules. Strict Mode has no effect in production, so it won’t slow down the app for your users. To opt into Strict Mode, you can wrap your root component into - it’s completely fine to change variables and objects that you’ve just created while rendering.This is called
local mutation—it’s like your component’s little secret. export default function TeaGathering() { let cups = []; for (let i = 1; i <= 12; i++) { cups.push(<Cup key={i} guest={i} />); } return cups; }
- Even though event handlers are defined inside your component, they don’t run during rendering! So event handlers don’t need to be pure.