Firstly install npm install create-react-app -g
. So that you will be able to create or run the react application for any folder on you machine.
Create react project create-react-app react-starter
run the command space and provide your application name. So this command creates the react application. And automatically set up the necessary development server babel and web pack. The development server helps us to execute react applications after compilation.
Webpack package help us to bundle the files. And babel package help us to compile the JavaScript files. From JSX file into regular plain JavaScript files.
So those compiled JavaScript files can be really execute on the browser.
After creating the react application you can use either of these commands like npm start, npm run build, npm test, npm run eject.
So make sure you're in the correct folder that react-starter
. And run the command npm start
This will automatically compile and execute the react application in the default browser.
Open the project in any Editor. And in this folder you can see something called public src.
In the public folder you can see index.html
. This will be the starting point of your react application. So it contains the typical html syntax. And it imports the icon and contains the basic meta tag.
We have tag called div tag with id=root
. This div tag is the placeholder where the actual react output will be rendered at runtime.
And after that there is nothing much. Just closing of body and html.
And now coming the src folder. You have something called index.js
which has statement called root.render
which eventually invoke app. That means it renders the app component in the root element which ins already present in the index.html
file.
So where is the definition of the app component? Go to app.js
file in the src folder. There you can see something called App. And is has a div tag that renders all the relevant output that we have seen in the browser.
Nested Components (App.js)
import './App.css';
import React, { Component } from 'react';
import { Button } from 'react-bootstrap'
import NavBar from './NavBar';
import MainContent from './MainContent';
export class App extends Component {
render(){
return (
<div className="App">
<React.Fragment>
<NavBar/>
<MainContent />
</React.Fragment>
</div>
);
}
}
export default App;
State
State is is the property that contains the content of your component, which you want to render on the page, or it may contain the information that you want to read from the user as well.
Let me add a property called state.
MainContent.jsx
import { Component } from "react";
export default class MainContent extends Component{
state = {}
render(){
return(
<div>Main Content</div>
)
}
}
state = {} this is the object literal in JavaScript, which can contain properties and property values can be of any type. Added a property into state.
state = {
appTitle: "Customers"
}
How do you render the value of the property from state. Open the braces and close the braces. That means your access in the state property of the current working class.
Example
render(){
return(
<div>
<h3>{this.state.appTitle}</h3>
</div>
)
}
Here the this keyword represents the current working object of the current class.
Now title is showing dynamically by using expressions.
Handle Event
In order to render the same, I just write the span tag. So inside this span tag, I would like to render the value of customers control and dynamically by using react expression
state = {
pageTitle: "Customers",
customerCount: 5
}
render(){
return(
<div>
<h3 className="border-bottom m-1 p-1">{this.state.pageTitle} <span className="badge bg-secondary">{this.state.customerCount}</span></h3>
</div>
)
}
Output
So every time when you modify the value of this property automatically, the same gets reflected in this place where the render the particular component property.
In JavaScript, we have events such as click, double click, focus, blur, key press etc. You can handle almost all types of events by using react.
You cannot call the methods of another component inside this present component. For example, let me add a button inside the h4 component
When the user clicks on this particular refresh button, I would like to call a method.
import { Component } from "react";
export default class MainContent extends Component{
state = {
pageTitle: "Customers",
customerCount: 5
}
render(){
return(
<div>
<h4 className="border-bottom m-1 p-1">{this.state.pageTitle}
<span className="badge bg-secondary m-2">{this.state.customerCount}</span>
<button className="btn btn-info" onClick={this.onRefreshClick}>Refresh</button>
</h4>
</div>
)
}
// executes when the user clicks on Refresh button
onRefreshClick(){
console.log("Refresh Click")
}
}
Here I can call any method that is present within the same component.
So as you can see, when you click on the button, you can see a refresh quickly in the browser console.
Update Component State
In order to update the state of the page, we have to use setState method but should not overwrite the values of the state property directly. Initial state value:
state = {
pageTitle: "Customers",
customerCount: 5
}
onRefreshClick(){
console.log("Refresh Click")
this.setState()
}
In this case, it is a very different matter. It is pre-defined method setState(). And you can supply only the property values which want to really update.
onRefreshClick(){
console.log("Refresh Click")
this.setState({
customerCount: 8
})
}
When click the Refresh button, it is showing an error, saying cannot read property called state of undefined
.
The reason behind it in JavaScript by default, that this keyword context will be changed when it is indirectly called.
Something few change like that arrow function.
onRefreshClick = () => {
console.log("Refresh Click")
this.setState({
customerCount: 8
})
}
Render list
How do you show this particular array data.
state = {
pageTitle: "Customers",
customerCount: 5,
customers: [
{id: 1, name: "Bipon Biswas", phone: "123-456"},
{id: 2, name: "Mead Fahim", phone: "345-456"},
{id: 3, name: "Mahfuzur Rahman", phone: "986-456"},
{id: 4, name: "Nayem Ahmed", phone: "432-456"},
{id: 5, name: "Sajib Biswas", phone: "762-456"},
]
}
The map method of JavaScript, every resource and arrow function and execute that arrow function for each element inside the area.
<table className="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Customer Name</th>
<th scope="col">Phone</th>
</tr>
</thead>
<tbody>
{this.state.customers.map((c) => {
return(
<tr key={c.id}>
<td>{c.id}</td>
<td>{c.name}</td>
<td>{c.phone}</td>
</tr>
)
})}
</tbody>
</table>
Conditionally Rendering
{this.state.customers.map((c) => {
return(
<tr key={c.id}>
<td>{c.id}</td>
<td>{c.name}</td>
<td>{c.phone == null ? "No phone": c.phone}</td>
</tr>
)
})}
{this.state.customers.map((c) => {
return(
<tr key={c.id}>
<td>{c.id}</td>
<td>{c.name}</td>
<td>{c.phone == null ? <div className="bg-warning p-2">No phone</div>: c.phone}</td>
</tr>
)
})}
{this.state.customers.map((c) => {
return(
<tr key={c.id}>
<td>{c.id}</td>
<td>{c.name}</td>
<td>{c.phone ? (c.phone) : (<div className="bg-warning p-2 text-center">No phone</div>)}</td>
</tr>
)
})}
Render Method
<table className="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Customer Name</th>
<th scope="col">Phone</th>
</tr>
</thead>
<tbody>
{this.state.customers.map((c) => {
return(
<tr key={c.id}>
<td>{c.id}</td>
<td>{c.name}</td>
<td>{this.getPhoneToRender(c.phone)}</td>
</tr>
)
})}
</tbody>
</table>
getPhoneToRender(phone){
if(phone){
return phone
}
else{
return <div className="bg-warning p-2 text-center">No phone</div>
}
}
Conditionally Rendering (Functional Component)
import { Fragment } from "react";
function ListGroup() {
let items = ["Dhaka", "Khulna", "Rajshai", "Albania", "Berlin"];
items = [];
// if(items.length === 0){
// return <><h2>List</h2><p>No item found</p></>
// }
// const message = items.length === 0 ? <p>No Item Found</p>: null;
const getMessage = () => {
return items.length === 0 ? <p>No Item Found</p>: null;
}
return (
<>
<h2>List</h2>
{items.length === 0 ? <p>No Item Found</p>: null}
{/* {message} */}
{/* {getMessage()} */}
<ul className="list-group">
{items.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
</>
);
}
export default ListGroup;
Top comments (7)
Two notes:
You should not install
create-react-app
globally. That was the advice a couple of years ago. The problem is: you need to keep it updated manually and it wastes space on your computer.Nowadays its the better idea to run it directly through npx:
npx create-react-app my-app-name
And the second note:
Especially as a beginner, you should not apply a class based approach in your react development.
Again, this was best practice a couple of years ago but not anymore.
A beginner should focus on functional components nowadays - class components might even get removed at some point.
Thank you so much for your tips.
The use of classes and state like this is oldschool React, please use an up-to-date tutorial and make use of the available hooks
I love it!
Thank you. @tarevcio
Very clear for us as beginner. Thank you
Thank you so much.