DevNotes

DevNotes

@devnotes ·

React Part 1: What React is, and your first app

React is a JavaScript library for building user interfaces out of small, reusable pieces called components. It was made at Facebook, and it runs a big part of Facebook and Instagram today.

Why React exists

In the JavaScript series, you changed the page by hand: find the element, change its text, add a class, append a new item. That's fine for a like button. In a big app, with a cart, a feed, notifications and a chat all open at once, keeping every corner of the page in step with your data by hand gets messy fast.

React turns it around. You describe what the page should look like for the data you have right now, and when the data changes, React updates the page to match. You stop writing "change this element" and start writing "here's how it looks".

Components

A React app is built from components: your own pieces, like a Navbar, a ProductCard or a CommentBox. Each one is a JavaScript function that returns what it should show:

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

That HTML-looking part is JSX. It looks like HTML but is JavaScript underneath, and the next part covers its rules.

What you need first

Install Node.js, the LTS version, from nodejs.org. It comes with npm, which downloads packages and runs your project. Check both worked by typing these in a terminal:

Bash
node -vnpm -v

Create a project

Vite is a tool that sets up a React project and runs it in your browser while you work:

Bash
npm create vite@latest my-app -- --template react

It asks two questions. For "Which linter to use?", the first option is fine. For "Install with npm and start now?", choose Yes: it downloads what the project needs and starts it. It then prints a local address, usually http://localhost:5173. Open it and you'll see the starter app.

Keep that terminal running while you work, and stop it with Ctrl+C when you're done. Next time, start it again from the same place with:

Bash
cd my-appnpm run dev

What's inside

The files that matter for now:

  • index.html: an almost empty page with a <div id="root"> in it.
  • src/main.jsx: puts your app into that div.
  • src/App.jsx: the main component, and where you'll start.

Open src/App.jsx, delete everything in it, and write:

JSX
function App() {  return (    <main>      <h1>My first React app</h1>      <p>Built by Asha.</p>    </main>  );}
export default App;

Save, and the browser updates by itself, without a refresh. export default App is what lets main.jsx import this component and show it.

Try it

Create the project and replace App.jsx as above, with your own name in it. Add a second paragraph. Then open DevTools and look at the Elements panel: in the end it's plain HTML, written for you by React.


Next: React Part 2: Components and JSX

reactjavascriptwebdevbeginners

Join WIK to like and reply to DevNotes and see more like this.