Components are individual pieces of a web page interface like:
Imagine an application with several parts.
For every change in the components React:
This lets you as the programmer:
React builds and handles changes to the elements on the page through several methods native to React components the most common of which are:
We can access these methods using React hooks to make our component do whatever we want when it loads, changes, or is removed from the page. More on hooks later!
React lets you to declare what you want the page to be.
Declarative means that you do not instruct the computer about what steps to take in order to achieve your desired result.
Declarative is different than Imperative code which:
An imperative example would be manipulating the DOM like this:
// When the Winow 'load' event fires, run the following JavaScript
(window.onLoad = function() {
// Create the H1 Element
const heading = document.createElement('h1');
// Create the Text node and content
const text = document.createTextNode('Hello DOM!');
// Add the Text node to the parent H1
heading.appendChild(text);
// Add the H1 Element to the Body Element
document.body.appendChild(heading);
})()
ReactDOM.render(
<div>
<h1>Reasons to love React!</h1>
<ul>
<li>Easier</li>
<li>Reliable</li>
<li>Fast</li>
</ul>
</div>,
document.getElementById('root'));
Hold up! What's that stuff that looks like HTML doing in my JavaScript!
It's not really HTML, it's JSX which is:
{}
Accepts a description of the components that make up the page, and what DOM node to render the results to.
// Render function on ReactDOM
ReactDOM.render()
// API signature
ReactDOM.render(
element,
container,
[callback] /* Optional*/
)
element
=> The DOM element and children to generate.container
=> What DOM element to generate within.callback
=> Optional function to call after generation.Under the hood React is compiling the JSX into HTML using the createElement
method which accepts an element type, props of the element, and child elements, and creates corresponding HTML elements.
// CreateElement function on ReactDOM
React.createElement()
// API signature
React.createElement(
type,
[props], /* Optional*/
[...children] /* Optional*/
)
type
=> A DOM element name like div
, form
or h1
.props
=> The element attributes like id
, class
, placeholder
, onChange
, or onSubmit
.children
=> Child elements to nest within the generated element.React allows you to:
/