title | publishDate |
---|---|
React Basics |
2023-08-09 |
This totorial is a complete guide core react constructs.
It demonstratens simple implementations of ReactDom
, React Element
, React Component
, props
, in a familiar, real-world component.
- CodeSandbox Used by me (Vim support)
- StackBlitz
React is "just JavaScript". Add it to any page on the internet.
Start with a simple HTML page like this:
<!-- my-page.html -->
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>React playground</title>
</head>
<body></body>
</html>
React needs a bridge between JavaScript and the DOM. Create a DOM node and query for it in a JavaScript script.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>React playground</title>
</head>
<body>
<!-- 1. Add an element with id -->
+ <div id="root"></div>
<!-- 2. Add a script tag -->
+ <script>
// 3. Capture a reference to element we'd like to control with JavaScript
+ let domNode = document.getElementById("root");
+ </script>
</body>
</html>
Reference: HTML-only template from React Docs, react.dev. Updated for ES Modules.
The browser has progressed a lot in a decade.
Specifying type="module"
on script tags to use modern JavaScript imports.
<body>
<div id="root"></div>
<!-- Specify type module -->
<script type="module">
let domNode = document.getElementById("root");
console.log(domNode);
</script>
</body>
Reference: Applying the module to your HTML, MDN.
Services like esm.sh allow us to import JavaScript modules from a CDN — no bundling 🥳.
Import the react-dom
module from the esm.sh.
// Import `react-dom@18` from esm.sh
+import ReactDOM from "https://esm.sh/react-dom@18.2.0";
let domNode = document.getElementById('root');
Reference: import API reference, MDN.
React needs to set up event handlers the root DOM node.
Prepare the root DOM node with ReactDOM.createRoot()
.
import ReactDOM from "https://esm.sh/react-dom@18.2.0";
let domNode = document.getElementById('root');
// Register root element with ReactDOM
+ReactDOM.createRoot(domNode);
Reference: React.createRoot API reference, react.dev.
At this point we can render plain text to the React root. Render "Hello ReactDOM" to the React root.
import ReactDOM from "https://esm.sh/react-dom@18.2.0";
let domNode = document.getElementById('root');
// Render plain text to React root
+ReactDOM.createRoot(domNode).render("Hello ReactDOM");
Reference: render API reference, react.dev.
Next we need React to create React elements and components.
Import react
and create a React element with React.createElement()
.
import ReactDOM from "https://esm.sh/react-dom@18.2.0";
+import React from "https://esm.sh/react@18.2.0";
+let reactElement = React.createElement("h1", {}, "Hello React");
let domNode = document.getElementById('root');
ReactDOM.createRoot(domNode).render("Hello ReactDOM");
Reference: createElement API reference, react.dev.
With a React element, we can render it to the React root.
Replace the rendered "Hello ReactDOM"
text with our new React element.
/* …react and react-dom imports… */
let reactElement = React.createElement("h1", {}, "Hello React");
let domNode = document.getElementById('root');
// render the React element to the React root
ReactDOM.createRoot(domNode).render("Hello ReactDOM"reactElement);
Reference: What is a React element, exactly?, react.dev.
React components are just functions that return React elements. Declare a new component and use it to create our React element.
let domNode = document.getElementById("root");
// 2. Create a React element from a the new component
-let reactElement = React.createElement("h1", {}, "Hello React");
+let reactElement = React.createElement(MyComponent);
// 1. Declare a new component
+function MyComponent() {
+ return React.createElement("h1", {}, "Hello React Component");
+}
ReactDOM.createRoot(domNode).render(reactElement);
Reference: Your first component, react.dev.
Static components, like static functions, are not useful.
Pass a name
prop to the React component and interpolate its value into the React element.
// 1. provide a prop object to the React component
let reactElement = React.createElement(MyComponent, { name: "React Rally" });
// 2. accept props
function MyComponent(props) {
return React.createElement(
"h1",
{},
`Hello React Component${props.name}`
);
}
let domNode = document.getElementById("root");
ReactDOM.createRoot(domNode).render(reactElement);
Reference: Passing props to a component, react.dev.
In addition to custom props, React components accept common props.
Pass an id
prop to the React component and apply it to the React element.
let reactElement = React.createElement(
MyComponent,
{
// 1. define id prop
+ id: "my_app",
name: "React Rally"
}
);
function MyComponent(props) {
return React.createElement(
"h1",
// 2. apply the id prop to the React element
{ id: props.id },
`Hello ${props.name}`
);
}
let domNode = document.getElementById("root");
ReactDOM.createRoot(domNode).render(reactElement);
Reference: Common component props, react.dev.
Not all common props use common HTML attributes.
Apply the class
HTML attribute to React elements using the DOM property name className
.
let reactElement = React.createElement(
MyComponent,
{
// 1. define class selectors using the className prop
+ className: "my-css-class-selector",
name: "React Rally"
}
);
function MyComponent(props) {
return React.createElement(
"h1",
// 2. apply the className prop to the React element
{ className: props.className },
`Hello ${props.name}`
);
}
let domNode = document.getElementById("root");
ReactDOM.createRoot(domNode).render(reactElement);
Reference: Element: className property, MDN.
Unlike HTML, the style
prop requires an object instead of a string.
Apply the style
prop to React elements using an object with camelCased CSS properties.
let reactElement = React.createElement(MyComponent, {
// 1. define styles using object and camelCased CSS properties
+ style: { color: "red", backgroundColor: "black" },
name: "React Rally",
});
function MyComponent(props) {
return React.createElement(
"h1",
// 2. apply the style prop to the React element
{ style: props.style },
`Hello ${props.name}`
);
}
let domNode = document.getElementById("root");
ReactDOM.createRoot(domNode).render(reactElement);
Reference: Special component props, react.dev.
React does not use attribute style event names.
Add a click handler using the camelCased onClick
prop and a function.
let reactElement = React.createElement(MyComponent, {
// 1. define the onClick prop and pass a function
+ onClick: () => alert("heading clicked"),
name: "React Rally",
});
function MyComponent(props) {
return React.createElement(
"h1",
// 2. apply the onClick prop to the React element
{ onClick: props.onClick },
`Hello ${props.name}`
);
}
let domNode = document.getElementById("root");
ReactDOM.createRoot(domNode).render(reactElement);
Reference: Common component props, react.dev.
Writing props
before using every value is tedious.
Use object rest syntax to create variables for custom props and collect the rest into a new object.
let reactElement = React.createElement(MyComponent, {
onClick: () => alert("heading clicked"),
name: "React Rally",
});
// 1. create variables for prop names we want to access
// 2. assign the remainer key-values (rest) to an object
function MyComponent(props{ name, ...restProps }) {
return React.createElement(
"h1",
// 3. send the entire rest object to createElement
{ onClick: props.onClick }restProps,
// 4. use the `name` variable instead of object property access
`Hello ${props.name}`
);
}
let domNode = document.getElementById("root");
ReactDOM.createRoot(domNode).render(reactElement);
Reference: Object rest spread, v8.dev.
<iframe width="315" height="560" src="https://www.youtube.com/embed/iAvix-05ew0" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen ></iframe> Check out these videos for a quick reference on what we've covered here