Describing the UI – React (2024)

React is a JavaScript library for rendering user interfaces (UI). UI is built from small units like buttons, text, and images. React lets you combine them into reusable, nestable components. From web sites to phone apps, everything on the screen can be broken down into components. In this chapter, you’ll learn to create, customize, and conditionally display React components.

In this chapter

  • How to write your first React component
  • When and how to create multi-component files
  • How to add markup to JavaScript with JSX
  • How to use curly braces with JSX to access JavaScript functionality from your components
  • How to configure components with props
  • How to conditionally render components
  • How to render multiple components at a time
  • How to avoid confusing bugs by keeping components pure
  • Why understanding your UI as trees is useful

Your first component

React applications are built from isolated pieces of UI called components. A React component is a JavaScript function that you can sprinkle with markup. Components can be as small as a button, or as large as an entire page. Here is a Gallery component rendering three Profile components:

function Profile() { return ( <img src="https://i.imgur.com/MK3eW3As.jpg" alt="Katherine Johnson" /> );}export default function Gallery() { return ( <section> <h1>Amazing scientists</h1> <Profile /> <Profile /> <Profile /> </section> );}

Ready to learn this topic?

Read Your First Component to learn how to declare and use React components.

Read More

Importing and exporting components

You can declare many components in one file, but large files can get difficult to navigate. To solve this, you can export a component into its own file, and then import that component from another file:

import Profile from './Profile.js';export default function Gallery() { return ( <section> <h1>Amazing scientists</h1> <Profile /> <Profile /> <Profile /> </section> );}

Ready to learn this topic?

Read Importing and Exporting Components to learn how to split components into their own files.

Read More

Writing markup with JSX

Each React component is a JavaScript function that may contain some markup that React renders into the browser. React components use a syntax extension called JSX to represent that markup. JSX looks a lot like HTML, but it is a bit stricter and can display dynamic information.

If we paste existing HTML markup into a React component, it won’t always work:

export default function TodoList() { return ( // This doesn't quite work! <h1>Hedy Lamarr's Todos</h1> <img src="https://i.imgur.com/yXOvdOSs.jpg" alt="Hedy Lamarr" class="photo" > <ul> <li>Invent new traffic lights <li>Rehearse a movie scene <li>Improve spectrum technology </ul>

If you have existing HTML like this, you can fix it using a converter:

export default function TodoList() { return ( <> <h1>Hedy Lamarr's Todos</h1> <img src="https://i.imgur.com/yXOvdOSs.jpg" alt="Hedy Lamarr" className="photo" /> <ul> <li>Invent new traffic lights</li> <li>Rehearse a movie scene</li> <li>Improve spectrum technology</li> </ul> </> );}

Ready to learn this topic?

Read Writing Markup with JSX to learn how to write valid JSX.

Read More

JavaScript in JSX with curly braces

JSX lets you write HTML-like markup inside a JavaScript file, keeping rendering logic and content in the same place. Sometimes you will want to add a little JavaScript logic or reference a dynamic property inside that markup. In this situation, you can use curly braces in your JSX to “open a window” to JavaScript:

const person = { name: 'Gregorio Y. Zara', theme: { backgroundColor: 'black', color: 'pink' }};export default function TodoList() { return ( <div style={person.theme}> <h1>{person.name}'s Todos</h1> <img className="avatar" src="https://i.imgur.com/7vQD0fPs.jpg" alt="Gregorio Y. Zara" /> <ul> <li>Improve the videophone</li> <li>Prepare aeronautics lectures</li> <li>Work on the alcohol-fuelled engine</li> </ul> </div> );}

Ready to learn this topic?

Read JavaScript in JSX with Curly Braces to learn how to access JavaScript data from JSX.

Read More

Passing props to a component

React components use props to communicate with each other. Every parent component can pass some information to its child components by giving them props. Props might remind you of HTML attributes, but you can pass any JavaScript value through them, including objects, arrays, functions, and even JSX!

import { getImageUrl } from './utils.js'export default function Profile() { return ( <Card> <Avatar size={100} person={{ name: 'Katsuko Saruhashi', imageId: 'YfeOqp2' }} /> </Card> );}function Avatar({ person, size }) { return ( <img className="avatar" src={getImageUrl(person)} alt={person.name} width={size} height={size} /> );}function Card({ children }) { return ( <div className="card"> {children} </div> );}

Ready to learn this topic?

Read Passing Props to a Component to learn how to pass and read props.

Read More

Conditional rendering

Your components will often need to display different things depending on different conditions. In React, you can conditionally render JSX using JavaScript syntax like if statements, &&, and ? : operators.

In this example, the JavaScript && operator is used to conditionally render a checkmark:

function Item({ name, isPacked }) { return ( <li className="item"> {name} {isPacked && '✅'} </li> );}export default function PackingList() { return ( <section> <h1>Sally Ride's Packing List</h1> <ul> <Item isPacked={true} name="Space suit" /> <Item isPacked={true} name="Helmet with a golden leaf" /> <Item isPacked={false} name="Photo of Tam" /> </ul> </section> );}

Ready to learn this topic?

Read Conditional Rendering to learn the different ways to render content conditionally.

Read More

Rendering lists

You will often want to display multiple similar components from a collection of data. You can use JavaScript’s filter() and map() with React to filter and transform your array of data into an array of components.

For each array item, you will need to specify a key. Usually, you will want to use an ID from the database as a key. Keys let React keep track of each item’s place in the list even if the list changes.

import { people } from './data.js';import { getImageUrl } from './utils.js';export default function List() { const listItems = people.map(person => <li key={person.id}> <img src={getImageUrl(person)} alt={person.name} /> <p> <b>{person.name}:</b> {' ' + person.profession + ' '} known for {person.accomplishment} </p> </li> ); return ( <article> <h1>Scientists</h1> <ul>{listItems}</ul> </article> );}

Ready to learn this topic?

Read Rendering Lists to learn how to render a list of components, and how to choose a key.

Read More

Keeping components pure

Some JavaScript functions are pure. A pure function:

  • 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.

By strictly only writing your components as pure functions, you can avoid an entire class of baffling bugs and unpredictable behavior as your codebase grows. Here is an example of an impure component:

let guest = 0;function Cup() { // Bad: changing a preexisting variable! guest = guest + 1; return <h2>Tea cup for guest #{guest}</h2>;}export default function TeaSet() { return ( <> <Cup /> <Cup /> <Cup /> </> );}

You can make this component pure by passing a prop instead of modifying a preexisting variable:

function Cup({ guest }) { return <h2>Tea cup for guest #{guest}</h2>;}export default function TeaSet() { return ( <> <Cup guest={1} /> <Cup guest={2} /> <Cup guest={3} /> </> );}

Ready to learn this topic?

Read Keeping Components Pure to learn how to write components as pure, predictable functions.

Read More

Your UI as a tree

React uses trees to model the relationships between components and modules.

A React render tree is a representation of the parent and child relationship between components.

Describing the UI – React (1)

Describing the UI – React (2)

Components near the top of the tree, near the root component, are considered top-level components. Components with no child components are leaf components. This categorization of components is useful for understanding data flow and rendering performance.

Modelling the relationship between JavaScript modules is another useful way to understand your app. We refer to it as a module dependency tree.

Describing the UI – React (3)

Describing the UI – React (4)

A dependency tree is often used by build tools to bundle all the relevant JavaScript code for the client to download and render. A large bundle size regresses user experience for React apps. Understanding the module dependency tree is helpful to debug such issues.

Ready to learn this topic?

Read Your UI as a Tree to learn how to create a render and module dependency trees for a React app and how they’re useful mental models for improving user experience and performance.

Read More

What’s next?

Head over to Your First Component to start reading this chapter page by page!

Or, if you’re already familiar with these topics, why not read about Adding Interactivity?

Describing the UI – React (2024)
Top Articles
Microsoft is testing a built-in crypto wallet in Microsoft Edge
Will Coinbase Refund Your Crypto if You're Scammed?
Somboun Asian Market
Uti Hvacr
Big Spring Skip The Games
Autobell Car Wash Hickory Reviews
Nikki Catsouras Head Cut In Half
Progressbook Brunswick
Alaska Bücher in der richtigen Reihenfolge
Craigslist Labor Gigs Albuquerque
Santa Clara Valley Medical Center Medical Records
Crusader Kings 3 Workshop
Shuiby aslam - ForeverMissed.com Online Memorials
Reddit Wisconsin Badgers Leaked
Dutchess Cleaners Boardman Ohio
House Of Budz Michigan
Cinebarre Drink Menu
1-833-955-4522
Ibukunore
Keurig Refillable Pods Walmart
Earl David Worden Military Service
Kaitlyn Katsaros Forum
Purdue 247 Football
Morse Road Bmv Hours
FAQ's - KidCheck
Roseann Marie Messina · 15800 Detroit Ave, Suite D, Lakewood, OH 44107-3748 · Lay Midwife
HP PARTSURFER - spare part search portal
Cvs Sport Physicals
Street Fighter 6 Nexus
Myra's Floral Princeton Wv
Ellafeet.official
Most popular Indian web series of 2022 (so far) as per IMDb: Rocket Boys, Panchayat, Mai in top 10
Wbli Playlist
That1Iggirl Mega
Hell's Kitchen Valley Center Photos Menu
Pensacola Cars Craigslist
888-333-4026
Froedtert Billing Phone Number
Ferguson Employee Pipeline
Craigslist Boats Dallas
Lonely Wife Dating Club בקורות וחוות דעת משתמשים 2021
Achieving and Maintaining 10% Body Fat
Top 40 Minecraft mods to enhance your gaming experience
Tinfoil Unable To Start Software 2022
Pike County Buy Sale And Trade
Walmart 24 Hrs Pharmacy
The Plug Las Vegas Dispensary
Fallout 76 Fox Locations
ESPN's New Standalone Streaming Service Will Be Available Through Disney+ In 2025
Vrca File Converter
Tamilyogi Cc
Cataz.net Android Movies Apk
Latest Posts
Article information

Author: Trent Wehner

Last Updated:

Views: 6195

Rating: 4.6 / 5 (56 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Trent Wehner

Birthday: 1993-03-14

Address: 872 Kevin Squares, New Codyville, AK 01785-0416

Phone: +18698800304764

Job: Senior Farming Developer

Hobby: Paintball, Calligraphy, Hunting, Flying disc, Lapidary, Rafting, Inline skating

Introduction: My name is Trent Wehner, I am a talented, brainy, zealous, light, funny, gleaming, attractive person who loves writing and wants to share my knowledge and understanding with you.