React Course Notes By Absar
. React Course .
Installation From Scratch:
Install Node js
Install VS Code
Open up terminal
npm init -y
npm install react react-dom
npm install @babel/core @babel/preset-env @babel/preset-react babel-loader
Cr file in root dir .babelrc
Code:
{
"presets": ["@babel/preset-react", "@babel/preset-env"]
}
npm install webpack webpack-cli webpack-dev-server
Cr file in root dir webpack.config.js
https://github.com/developedbyed/simple-react-setup/blob/master/webpack.config.js
Code:
const HtmlWebpackPlugin = require("html-webpack-plugin");
const path = require("path");
module.exports = {
entry: "./src/index.js",
output: {
filename: "bundle.[hash].js",
path: path.resolve(__dirname, "dist"),
},
plugins: [
new HtmlWebpackPlugin({
template: "./src/index.html",
}),
],
resolve: {
modules: [__dirname, "src", "node_modules"],
extensions: ["*", ".js", ".jsx", ".tsx", ".ts"],
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: require.resolve("babel-loader"),
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
},
{
test: /\.png|svg|jpg|gif$/,
use: ["file-loader"],
},
],
},
};
Cr folder in root dir src/App.js
Code:
import React from "react";
const App = () => ( // directly returning
<div>
<h1 className="wow">Hello React !!!!!</h1>
</div>
);
export default App;
Cr src/index.js
Code:
import React from "react";
import ReactDOM from "react-dom";
//Import App
import App from "./App";
ReactDOM.render(<App />, document.querySelector("#root"));
Cr src/index.html
Code:
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>React</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
package.json
Code:
"scripts": {
"start": "webpack-dev-server --hot --open",
"build": "webpack --config webpack.config.js --mode production"
},
npm install html-webpack-plugin
npm run build for when site is ready
npm install style-loader css-loader
To add css first Cr App.css file and then import that one in App.js
Code:
import "App.css";
npm install –dev file-loader;
To add an image first install file loader then import image and then you can use it in your project
Code:
import thumb from "./thumb1.jpg";
<img src={thumb} alt="" />
Simple Setup => npx create-react-app simple-react(project-name)
What are props?
So basically props are just properties like href className and so on however we can create our own attributes or props or properties
Why do we use props? Basically it is the way to pass data b/w components
How can we pass data?
We can not pass props down to up but we can pass up to down
What i mean by that is very simple and that I can pass props to app but i can pass props to components imported in App.js and then I can access them
An example of passing data:
What is the state?
It’s a JS object that contains a piece of data. You can imagine it as a variable in react app and when the state changes then the component re-render itself and creates change as respected to state. Like if a navbar has a state of false so when it gets true it will automatically change itself.
So It automatically react to the changes
Deep Discussion on state in react js:
state is a javascript object that contains a piece of data now i don't like to explain it this way i'm just going to explain it the way i know you can imagine it as just a variable in a react app the difference is though that this state or variable reacts to changes so if something happens in your app if that piece of variable or state gets updated, the component is automatically gonna re-render and your component and your whatever you see on the screen is gonna automatically update and react to that change okay so basically what the state is you can imagine like in your app here you have a piece of state that is maybe tells you that a navbar is true or false okay, so it has a piece of data that's true or false and if it's true your actual app is automatically going to react to it that's why we have the name react it's automatically going to react to the changes so basically how you write react code is you lay down kind of the foundation here and based on your state
So it won’t update the counter but when we use state and when the state changes the component re-renders only that part where it is necessary itself and reacts accordingly.
Example # 2 (Toggle Logic)
REACT Projects
Project # 01 (Feedback App) Brad Traversy Udemy Course
https://github1s.com/bradtraversy/feedback-app/blob/main/src/index.css#L1-L231
Install This extension
Creating Components:
Cr src/components/Header.jsx
Type rfce (We don’t need importing react here)
Import Header.jsx in src/App.js
If we want to pass prop to Header Component then we can simply do it like attributes <Header text=”Hello World” /> and if we can to access it inside Header Component then we can just simply add Header(props){...} or Header({ text }){...} so here we are destructuring it and we can use it anywhere inside the function in {} (curly braces) because we know that if we wanna write js code inside JSX then we simply put braces there.
Default Props =>
PropTypes in React => Basically we used it for extra checking like type checking of the prop values so u could specify whether it could be string or number
Type impt to import prop type checker
Then type this and if you want this prop to be required there then you can type PropTypes.string.isRequired
Paste this given code inside index.css:
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700&display=swap');
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: 'Poppins', sans-serif;
background-color: #202142;
color: #fff;
line-height: 1.6;
}
ul {
list-style: none;
}
.container {
max-width: 768px;
margin: auto;
padding: 0 20px;
}
header {
height: 70px;
width: 100%;
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 30px;
}
.card {
background-color: #fff;
color: #333;
border-radius: 15px;
padding: 40px 50px;
margin: 20px 0;
position: relative;
}
.card.reverse {
background-color: rgba(0, 0, 0, 0.4);
color: #fff;
}
.card h2 {
font-size: 22px;
font-weight: 600;
text-align: center;
}
.rating {
display: flex;
align-items: center;
justify-content: space-around;
margin: 30px 0 40px;
}
.rating li,
.num-display {
position: relative;
background: #f4f4f4;
width: 50px;
height: 50px;
padding: 10px;
text-align: center;
border-radius: 50%;
font-size: 19px;
border: 1px #eee solid;
transition: 0.3s;
}
.rating li label {
position: absolute;
top: 50%;
left: 50%;
width: 50px;
height: 50px;
padding: 10px;
border-radius: 50%;
transform: translate(-50%, -50%);
cursor: pointer;
}
.rating li:hover,
.num-display {
background: #ff6a95;
color: #fff;
}
[type='radio'] {
opacity: 0;
}
[type='radio']:checked ~ label {
background: #ff6a95;
color: #fff;
}
.input-group {
display: flex;
flex-direction: row;
border: 1px solid #ccc;
padding: 8px 10px;
border-radius: 8px;
}
input {
flex-grow: 2;
border: none;
font-size: 16px;
}
input:focus {
outline: none;
}
.feedback-stats {
color: #fff;
display: flex;
justify-content: space-between;
align-items: center;
}
.num-display {
position: absolute;
top: -10px;
left: -10px;
}
.close,
.edit {
position: absolute;
top: 10px;
right: 20px;
cursor: pointer;
background: none;
border: none;
}
.edit {
right: 40px;
}
.btn {
color: #fff;
border: 0;
border-radius: 8px;
color: #fff;
width: 100px;
height: 40px;
cursor: pointer;
}
.btn-primary {
background-color: #202142;
}
.btn-secondary {
background: #ff6a95;
}
.btn:hover {
transform: scale(0.98);
opacity: 0.9;
}
.btn:disabled {
background-color: #cccccc;
color: #333;
cursor: auto;
}
.btn:disabled:hover {
transform: scale(1);
opacity: 1;
}
.message {
padding-top: 10px;
text-align: center;
color: rebeccapurple;
}
/* FIX: Remove position: absolute to keep about icon at the bottom of the
* document */
.about-link {
display: flex;
justify-content: flex-end;
}
/* FIX: Remove position: absolute to keep about icon at the bottom of the
* document */
.about-link a {
color: #fff;
cursor: pointer;
}
.about-link a:hover {
color: #ff6a95;
}
.about h1 {
margin-bottom: 20px;
}
.about p {
margin: 10px 0;
}
@media (max-width: 600px) {
.rating li {
margin: 10px 3px;
}
.rating {
display: flex;
align-items: center;
justify-content: center;
flex-wrap: wrap;
margin: 30px 0 40px;
}
.input-group input {
width: 80%;
}
}
Going back to Header.jsx file Let’s see how we can add inline css in React <header style={{ backgroundColor: ‘blue’, color: ‘red’ }}>
Then if we need to give them styles internal not inline then we will use this approach:
If you want to pass styles from props then we will simply pass props to <Header bgColor=’red’ textColor=’blue’ /> component and then destruct them and then use them like:
Use default props for styling:
Remove props from Header
Then add this:
So here we have added default props and some additional checks to it
We have 2 types of state
App level State or Global level State (The State we use in multiple components)
Component Level State (The Data that is just associated to only that component)
Cr components/FeedbackItem.jsx
rfce
Code:
Let’s Bring it into the App.js and remove h1 tag:
So here we are going to use hooks Sate Hook All Hooks Starts with use like useState
So Write in FeedbackItem.jsx import {useState} from ‘react’
Like This
You can see this by react developer tools from inspect
If you want to change state so can do it with setRating or setText or whatever the name of your state is just like in the example:
So here we are passing value and returning it and also accessing previous value from the parameter
App level State: in App.js
Cr data/FeedbackData.js
const FeedbackData = [
{
id: 1,
rating: 10,
text: 'Lorem ipsum dolor sit amet consectetur adipisicing elit. consequuntur vel vitae commodi alias voluptatem est voluptatum ipsa quae.',
},
{
id: 2,
rating: 9,
text: 'Lorem ipsum dolor sit amet consectetur adipisicing elit. consequuntur vel vitae commodi alias voluptatem est voluptatum ipsa quae.',
},
{
id: 3,
rating: 8,
text: 'Lorem ipsum dolor sit amet consectetur adipisicing elit. consequuntur vel vitae commodi alias voluptatem est voluptatum ipsa quae.',
},
]
export default FeedbackData
Import this data file in App.js like import FeedbackData from ‘./data/FeedbackData’
Then pass this data inside state like const [feedback, setFeedback] = useState(FeedbackData)
Now in browser React Developer Tools you can see when you click on app you can surely see states data under state section
Now let’s create a new component that is gonna be FeedbackList.jsx that will map through all items, just like we are displaying one item right now
Cr components/FeedbackList.jsx
rfce
Remove importing FeedbackItem because we are gonna so many so we will import FeedbackList instead of FeedbackItem like:
Then we are gonna pass prop to FeedbackList component like <FeedbackList feedback={feedback} />
Then we will get the value of feedback by destructing it and we check values by console log.
And we can use an if statement to check if there is is feedback or not and display message accordingly
Like
Then import feedbackItem inside FeedbackList and then map through those items e.g.
So inside FeedbackItem component the data is still hard coded in state
So we don’t need any state here because the data is coming through Props
So we will just remove the state hook and state
Then destructure the data that is coming from props like FeedbackItem({ item }) {...}
Then we will display it by item.rating and item.text
Card Component
Cr src/components/shared/Card.jsx
rfce
Use children prop to get nested data of Card
Import Card component inside FeedbackItem.jsx
How to Use conditional Classes
So first pass prop to the Card to reverse={true}
Destructuring the reverse in Card.jsx
In index.css
.card.reverse{
background-color:rgba(0,0,0,0.4);
color:#fff;
}
Use template String on className like
So if reverse is true then the color will be changed
Conditional Styles:
So now I’m gonna remove the reverse prop from the Card Component and Then use the default prop in Card.jsx
Now if I change the reverse to true then the color mode will be set to dark
So this is additional check but you don’t have to do use them, these are just extra checks if you want to include its up to you
Now let’s add some Delete Functionality (CRUD => DELETE part)
Events & Prop Drilling
First we need cross icon on the top right side of the card so we need to install icons npm i react-icons
Now we need to import the icon where we wanted to use it so in our case we are going to use it in FeedbackItem.jsx import { FaTimes } from ‘react-icons/fa’
So now we are going to use it as a component like
Now we can use its props like color e.g. <FaTimes color=’purple’ />
onClick Functions
<button onClick={()=> console.log(item.id)}>
For separate function we can do a little different so we just write the name of the function inside curly braces like <button onClick={handleClick}> and then just before return statement we can define a function
Now let’s delete our feedback items => so this click suppose to delete that particular item but the problem is that we don’t have feedback item in the FeedbackList instead we have the Feedback Items that are coming from the App.js but the problem we can’t directly pass prop here so now we are gonna use prop drilling method that looks something messy at first but we’ll use context api to handle this issue later on
We have to go upwards
So in FeedbackList we are gonna pass a prop that is having a function as a value handleDelete={(id) => {console.log(id)}} in FeedbackItem component
Now in FeedbackItem we pass handleDelete as a parameter to access its value and then i just simply pass handleDelete function on the button just like this:
Now if we click on the button then the console log is coming from the FeedbackList.jsx but there is also no feedback the feedback is one level up to App.js so let's call this handleDelete that is in the FeedbackList.jsx to handleDelete as a value like:
And this prop is gonna pass in here
So now in the App.js we are going to use that handleDelete by passing it a prop to FeedbackList component:
Now we are going to create a function in App.js of deleteFeedback pass the parameter id in here and console log it like
Now just use the filter high order method here:
Comments
Post a Comment