Introduction to React

Basic components and state

Basic components and state

JSX

JSX is a syntax extension used by React to create UI elements. You can kind of think of it as "HTML tags within JS" (except they're actual JS elements). Its syntax doesn't differ a lot from HTML, but there are a few exceptions like the following:

  • HTML's class attribute becomes className
  • HTML's for attribute becomes htmlFor
  • and otherse

Components and Props

As introduced earlier, components are basically your self-written custom "HTML tags" that you can re-use. Every component usually gets their own file. Typical components would be navbars, buttons, data pickers, color pickers and so on. But also every route of your web app (like /about or /contact) will most likely get their own file. Your components can also receive props from their parent component to allow them to be more flexible.

Example component

navbar-item.js
import React from "react"
const NavBarItem = (props) => (
<a style={{ color: props.color, marginRight: "5px" }} href={props.href}>
{props.children}
</a>
)
export default NavbarItem

As you can see, the component is just an exported function that receives a props object. To use a JS expression (like a variable) within JSX, you have to put that expression within { }. props.children contains the element's children (Example: <b>Here are the b tag's children</b>)

You can the import the component in another file and use it:

App.js
import React from "react"
import NavbarItem from "./components/navbar-item"
const App = () => (
<div>
<NavbarItem href="/" color="blue">
Home
</NavbarItem>
<NavbarItem href="/about" color="red">
about
</NavbarItem>
<NavbarItem href="/contact" color="green">
contact
</NavbarItem>
</div>
)
export default App
Edit this page on GitHub

On this page