React part 1: Virtual DOM, JSX, and Components
What is React?
It's a javascript library developed by Facebook, used for frontend development. It handles the "view" / user-interface layer of web and mobile applications. React is maybe best known for the way in which it breaks up applications into various, reusable COMPONENTS. Imagine you open up your laptop and pop on over to facebook.com (an up-and-coming social network. it's like hipster-myspace). K, you're logged into your profile. What does the homepage look like? Here's a little diagram I drew:
Nice just developed carpal tunnel trying to doodle that.
Anyway. Look back at the beautiful hyper-realistic drawing. See how all of the different sections of the page are depicted in boxes? That's sort of the conceptual representation of React's philosophy/functionality -- Everything on the webpage can be designed as an individual and separate component. A NavBar
component, and a TrendingNews
component, and a StatusBox
component. Each of these individual components has its own individual functionality, its own data, and you can manipulate them individually.
Breaking an application into these modular building-blocks presents many advantages... better app speed / more efficient rendering, more scalability, flexibility, simplicity... a smoother user-experience -- You name it. Below are some of the specific features that make React... pretty neat.
THE VIRTUAL DOM:
The Virtual DOM is essentially a virtual copy of everything you see on a webpage. In React, every object on the page has a virtual replica of itself, that only exists as a representation of the object (i.e., it's not visible on the page). Why is that necessary? Well it's not explicitly necessary, but it's incredbily powerful, and it's one of the cornerstones that allows React to function as it does.
Remember the components we discussed above? In a React app, when you want a UI component to update (i.e. physically re-render on the screen with updated information), that re-render request causes a chain of events to take place.
- The entire virtual (invisible) DOM updates.
- The updated virtual DOM compares itself to the previous version.
- The virtual DOM then finds the elements/components that differ from the previous version, and tells the real DOM which components to update.
- Those components update and re-render on the real-DOM. ONLY those components.
You can contrast that to the way in which a lot of older websites might function: when you click on something on a webpage, that request might cause the ENTIRE real-DOM to re-render, rather than just the individual component you click on.
This might seem trivial, but physical page-rendering takes way more time / computer-power than virtual DOM maniuplation. By only re-rendering selected/individual components, React can make your app wayyyy faster, way smoother, and way more performant.
JSX:
What is JSX? It sort of looks like HTML / XML + Javascript code. React's official website describes JSX as a "syntax extension to Javascript," and it's frequently (almost always, as far as I know) used when writing React components. I'll illustrate with an example. Here's a React component I just started to work on (it's a 60-second countdown clock):
class Countdown extends Component {
constructor() {
super();
this.state = { secondsRemaining: 60 };
}
tick() {
this.setState(prevState => ({
seconds: prevState.secondsRemaining - 1
}));
}
timerColor() {
return this.state.secondsRemaining <= 10 ? "red" : "blue";
}
componentDidMount() {
this.interval = setInterval(() => this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
return (
<div className="countdown" style={{ color: this.timerColor() }}>
Seconds Remaining: {this.state.secondsRemaining}
</div>
);
}
}
Check out the last few lines, the ones inside the render()
block at the end of the component. That's JSX in there. I used this example to point out a couple features of JSX.
- It looks a lot like HTML or XML, using the same element tags (like
<div>
,<p>
, etc.). One important syntactical note is that JSX blocks must return a SINGLE parent element, i.e. the last closing tag, must close the first opening tag. Basically, if you want to render more than one element (like, say you have an<h1></h1>
AND a couple<p></p>
elements that you want to return), you need to wrap everything you want to render inside of a single parent element (often times you would just wrap everything in a<div>
). - You can write Javascript inside of JSX. In the
render()
function, see all the stuff inside curly-braces? Those evaluate as Javascript expressions. You can see we use this to set/change thestyle
attribute of thediv
.this.timerColor()
is a Javascript function (which we define a few lines above therender()
function) that returns a color based on how much time is left (here it turns the clock red when there are 10-seconds left -- DRAMA. Also did you notice the ternary operator in that function?). - We typically write JSX element attributes in camelCase (e.g.
className
), and there are some attributes that are specific to JSX/React.className = "some-class"
is the React equivalent toclass = "some-class"
in regular HTML.
There's plenty more to JSX, but I won't go any further in this post. Just wanted to familiarize you with what it is, and what it looks like.
COMPONENTS:
Let's dive just a tiny bit deeper into components.
I read a great article when I started learning React (I can't find it right now) that helped me conceptualize components... here's the gist:
React components are esentially just functions, like in any programming language. They can take input (in React, input can be either "properties" -- often written as props
-- or "state"), and they produce some kind of output. In React, component output is a description of a User Interface. What does that mean? Well, look at the Countdown
component I referenced above. The render()
function at the end returns JSX, which describes how the component should appear on the page.
Stateless vs. Stateful components in React:
React components are said to be stateless (aka a functional component) or stateful (aka a class component).
A Functional Component is, quite literally, just a javascript function. A basic functional component might look like this:
function Greeting(props) {
return <h1>Hello, {props.name}.</h1>;
}
Quick note, many developers might use ES6 arrow syntax to write a simple functional component. That would look like the code below, which does the exact same thing:
const Greeting = (props) => (<h1>Hello, {props.name}.</h1>);
When called, this functional component will take in props
as input, and then display a message that says "Hello, [name]" to whatever name it extracts from props. One thing to note is that it is React convention that props
are immutable (i.e. they should not be changed within the component). For instance, we would NOT say something like props.name = "Noah"
inside the body of the <Greeting>
component. That name will be inherited through through a prop
, like so:
const component = <Greeting name="Jacob" />;
ReactDOM.render(component, document.getElementById('root'));
The above will render a header element to the DOM with a message that reads "Hello, Jacob."
You might use a functional component to render a UI element that is pretty static, i.e. it doesn't really change. A real-world example might be a website <Footer />
that just displays static copyright info.
A Class Component is a bit more complex. It can still take props
as input, but the distinction is that class components have state
, which is NOT immutable (it can be changed/set within the body of the component). Consider the Countdown
component I illustrated earlier (go ahead and scroll up to look at it again) -- that is a stateful class component. I won't go deep into the syntax in this post, but a class component is initialized just as classes are in other Object-Oriented languages, with a constructor
function that contains the initial class attributes, or state (like secondsRemaining
in the Countdown
component). The state can be accessed by calling this.state
, and it can be updated by calling this.setState()
(look the tick()
function). In the Countdown
component, the state is updated every second, and re-rendered with the new secondsRemaining
. It will render initially as "Seconds remaining: 60", then one second later, you will see it update to "Seconds remaining: 59."
Components can be referenced and rendered within one-another. Consider the following example, which is typical of a standard React app:
class App extends Component {
render() {
return (
<Greeting name="Noah" />
<Countdown />
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
Here we render an App
component to the webpage, which in turn renders all of the components within the App
component body (Greeting
and Countdown
). The above code would render a page that reads "Hello, Noah.", and below that it would show the countdown clock.
Kk that's it for now. Soooooo many details not covered here, but hopefully a good introduction on why React is useful in web development, and a couple of the features that make it unique. I'll expand more in future posts.
Love you guys,
noah
Comments
Post a Comment