Hello DEV community!
Every time I start learning something new I always do a short list of main concepts in order to have it handy when diving deeper into other concepts. It really always comes in handy!
I started learning React few weeks ago and since then I committed that I will learn something new everyday and also, I decided that I will document this journey by sharing my own understandings and knowledge :)
This article is all about the core building block of React, such as:
- JSX
- Components
- State and props
- Conditional rendering
So, let's start!
JSX
Before starting to discussing any concept of React, we must always remember that everything in react is JS (JavaScript) even if doesn't look like it!
var jsx_element = <h1>hi!</h1>;
The variable declaration above, doesn't look either like HTML nor like JS, right?
That is because JSX is used, which is a syntax extension to JS, and in the end it all compiles to JS code using Babel (compiler for next-gen JS). Therefore, we can use any JS expressions such as variables, getting object properties or even calling functions within JSX code by enclosing it in curly braces '{}'.
var address = {
street: 'oxford street',
number: 14,
postcode: '3344'
city : 'London'
country: 'England'
}
const getAddress({street, number}) {
return street + ' ' + number;
}
const jsx_element = <div>
<h1>{getAddress(address)}</h1>
</div>;
ReactDOM.render(
jsx_element,
document.getElementById('root')
);
You can notice on the example above that the curly braces are used in order to fetch the address in as string type by calling the getAddress function within the JSX code.
Components
Components is a concept that helps to enforce the single-responsibility principle in React. We should think of components as reusable pieces of our application, where each one performs (ideally) exactly one responsibility/task. In simple words, a component is a function that accepts data (props) and specifies how those data should appear in UI.
A component can be either a class-based or a function-based.
Class-based
A class-based component is also known as a stateful component or container component and it is created as follows:
import React, Component from 'react';
class App extends Compoenent {
render() {
return(
/* <div>JSX</div> */
)
}
}
exports default App;
Function-based
They are called function-based because they are literally JavaScript functions. Also, these types of components are also referred as stateless or representational components (originally!) because they are best used to only display UI.
import React from 'react';
const App = () => {
return(
/* <div>JSX</div> */
)
}
exports default App;
The example uses a ES6 syntax, but a typical function is also a correct way of creating one. At the end, React is all JavaScript! Ideally, for performance reasons in a React app we should have few stateful components that manipulate state often, and many stateless components that only accept props and show UI.
Also, important to note that a function-based component can also be used as a stateful component. In simple words, Hooks enable the component to access the state by importing and using the useState (check out the resources to learn more).
State and props
Props
Passing data from one component to the other is done through properties or as known in React props. Meaning that, when a custom (not a DOM tag) component is used we can pass data to it by adding custom attributes to it. React passes the attribute to the component as an object where the attribute name is the key and it assigns to it the given value, e.g:
const App = () => {
return (
<div> <Person name="Tringa" lastName="Krasniqi"/> </div>
);
}
//it is actually passed as object
const Person = (props) => {
/*
props = {
name : "Tringa",
lastName : "Krasniqi"
}
*/
}
Important to note:
- props are READ-ONLY and should never be modified (that's where state comes in!).
- all react components should act like pure functions with respect to their props.
State
State allows components to change the output when a user action has taken place, or when we receive recent network data etc., without violating the above-mentioned rule. State properties are private and fully controlled by the component. Therefore, local and encapsulated within the component. When the state is changed in a component React triggers DOM render and updates the value in UI.
To use state correctly means that the following need to be followed:
- it should not be modified directly:
//(or this.props.name, if the data is passed)
this.state.name = "Tringa" //incorrect, although correct only when initialised in the constructor
setState({name: "Tringa"}) // correct
- state updates might be async, so many setStates will be run in batch and overriding the data. Therefore, use a function within the setState instead of an object, for e.g.:
setState((state, props) => {
//old state
//new data (notice, it is props)
})
- state updates are merged, so when calling it multiple times it replaces the specified data and merges them to the rest of the properties of the state object. E.g:
this.state = {
name : "Tringa",
lastName : "Krasniqi",
age : 24
}
setState({ name : "Jane" });
setState({ lastName : "Doe" });
/*
results in:
state = {
name : "Jane",
lastName : "Doe",
age : 24
}
*/
Conditional rendering
It is often needed in our application to show or hide various UI elements based on the state of the application. One common example would be:
- when user is logged out, the profile view should redirect to login form
- when the user is logged in, it should show the profile view with their info
To achieve this in React we use the JavaScript conditional if statement or ternary operator within the JSX code. Using the if statement example:
render() {
const button = <LogginButton onClick={this.handleLogin}/>
if(this.state.isLoggedIn) {
button = <LogoutButton onClick={this.handleLogout}/>
}
return (
<div>
{button}
</div>
);
}
The ternary operator is the short form of writing if conditional statements in one line of code, however it is not as readable as its long form. The syntax of this operator is:
condition ? expressionIfTRUE : expressionIfFALSE;
//and it is the same as:
if(condition) {
expressionIfTRUE;
} else {
expressionIfFALSE;
}
In our React case it would be used like in the following case:
render() {
return(
<div>
{
this.state.isLoggedIn ?
<LogoutButton onClick={this.handleLogout}/>
:
<Logginbutton onClick={this.handleLogin}/>
}
</div>
)
}
Apart from these, what's next?
Resources to learn more form:
- React documentation https://reactjs.org/docs/getting-started.html
- React course https://www.udemy.com/course/react-the-complete-guide-incl-redux/
- Component lifecycle https://www.freecodecamp.org/news/these-are-the-concepts-you-should-know-in-react-js-after-you-learn-the-basics-ee1d2f4b8030/
- Beginners guide https://dev.to/aspittel/a-complete-beginners-guide-to-react-2cl6
- React Hooks https://reactjs.org/docs/hooks-intro.html | https://reactjs.org/docs/hooks-reference.html
Other important concepts to learn:
- Component lifecycle
- Styling components
- React Hooks
Hope this article will help anyone that is on the same journey of learning React as me.
Any feedback/suggestion/correction will be highly appreciated.
Thank you for reading!
Top comments (6)
It should be specified that in functional components the state is available via
useState
hook and not withthis
. Also there should be some references to React Hooks due to the fact that that is the current way of doing things.state
Thank you a lot for your feedback :)
I tried my best to keep things as simple as possible and not mention Hooks or anything else and not explaining them. I implied that function-based components were originally created for display only (well, until Hooks came on the way). But, I will definitely add a link to React Hooks to anyone that is interested to know more.
Hi Tringa do you use `` backticks to enclose your code snippets in the markdown editor?
Hi Desmond :) Yeah I use the backticks and followed with javascript, like:
javascript
(three backticks)Nicely explained! Those resources are added bonus. 👏
So glad you enjoyed it ☺️