Skills / Front-end apps with React / Why React: components and a screen that follows your data

Front-end apps with React, lesson 1 of 8

Why React: components and a screen that follows your data

React is a JavaScript library for building user interfaces. It rests on two ideas.

1. Build from components. A component is a small, reusable piece of the interface: a button, a product card, a menu. In React a component is a JavaScript function that returns what to show. A page is just components inside components:

  • App contains a Header, a ProductList and a Footer
  • ProductList contains many ProductCard components, one per product

Build a ProductCard once and reuse it for every product. Fix a bug in it once and it is fixed everywhere.

2. The screen follows your data. In plain JavaScript you change the page step by step: find this element, change its text, add a class. In React you describe what the screen should look like *for the current data*, and React updates the page for you whenever the data changes. If the cart holds 3 items, you write "show the number of items in the cart", and when it becomes 4, React redraws that part.

Components are written in JSX, which looks like HTML inside JavaScript:

function Greeting() { return <h1>Hello, Asha</h1>; }

JSX has small differences from HTML: you write className instead of class, and you put JavaScript values inside curly braces, such as <p>{itemCount} items</p>.

Thinking in components is the most important React skill. Before writing code, sketch the screen and draw a box around each repeating or separate part.

Try it: Pick a shopping site and sketch its product page on paper. Draw boxes around the components you would build (for example Header, ImageGallery, PriceBox, ReviewList) and note which ones repeat.

Check yourself

1. What is a React component?

2. In JSX, what do you write instead of the HTML attribute class?

3. What happens in React when the data changes?