# MERN stack - the basics
## reactjs
first, we gonna start by creating a react app ->
```
npm init react-app my-app
cd my-app
npm start
```
we'll then be promoted to a live server.
- - -
**jsx:**
how the ui setup, it functions as html but it's pure js
- - - - -
the react app is separated by components instead of pages and files . each component is responsible of a specific functionality.
added in the js file:
1-what to render
```
<h1>hello dhay </h1>
```
2-where to render
```
document.getelementbyid("root")
```
```
ReactDOM.render(<h1>hello dhay</h1>, document.getElementById("root"))
```
```
//props(properties) means the input of a function
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
```
*spa = single page application
**package.json**
```
{ ...
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
... }
```
These scripts are executed with the `npm run <script>` command in an IDE-integrated terminal or command line tool. The run can be omitted for the start and test scripts.
- Runs the tests
`npm test`
- Builds the application for production
`npm run build`
----
functions should start with a uppercase
```
function Navbar() {
return (
'the thing we want to render on our html')
}
```
then ->
```
ReactDOM.render(
<div>
<Navbar />
</div>
, document.getElementById("root"))
```
----
**what you need to understand before diving into react**
* Components
* JSX
* State
* Props
https://www.freecodecamp.org/news/the-react-handbook-b71c27b0a795/
callback functions
Promises (ES6)
Async/Await (ES8)
## React Router
Components
The 3 components you will interact the most when working with React Router are:
* BrowserRouter, usually aliased as Router
* Link
* Route
BrowserRouter wraps all your Route components.
Link components are used to generate links to your routes
Route components are responsible for showing - or hiding - the components they contain.
```
import React from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter as Router, Link, Route } from 'react-router-dom'
const Dashboard = () => (
<div>
<h2>Dashboard</h2>
...
</div>
)
const About = () => (
<div>
<h2>About</h2>
...
</div>
)
ReactDOM.render(
<Router>
<div>
<aside>
<Link to="/">Dashboard</Link>
<Link to="/about">About</Link>
</aside>
<main>
<Route exact path="/" component={Dashboard} />
<Route path="/about" component={About} />
</main>
</div>
</Router>,
document.getElementById('app')
)
```
***Stateless Component***
```
// Stateless component
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
```
***Stateful Component***
```
class Car extends React.Component {
constructor(props) {
super(props);
this.state = {brand: "Ford"};
}
render() {
return (
<div>
<h1>My {this.state.brand}</h1>
</div>
);
}
}
```
---
# task 1
https://www.npmjs.com/package/cra-template
*Material UI* -> react library
*req1* design only
*req2*

^this is a stateless component
^ result card -> loop on the results, hidden
nav height -> 780 px
**we need state management**
pass data to child
^ this is a stateful component
*req3*
صعب 😞
header component inside -> layout
react router dom
https://reactrouter.com/en/main
*outlet is the core concept in the layout *
---
this.props.children -> used to display whatever you include between the opening and closing tags when invoking a component.
# state management ---
## useState Hook
```
import { useState } from "react";
function App() {
const [name, setName] = useState("Ihechikara");
// you have to create your state and give it an initial value (or initial state) which is "Ihechikara". The state variable is called name, and setName is the function for updating its value.
const changeName = () => {
setName("Chikara");
};
return (
<div>
<p>My name is {name}</p>
<button onClick={changeName}> Click me </button>
</div>
);
}
//the DOM has a paragraph containing the name variable and a button which fires a function when clicked. The changeName() function calls the setName() function which then changes the value of the name variable to the value passed in to the setName() function.
export default App;
```
### using usestate in forms
```
import { useState } from "react";
function App() {
const [name, setName] = useState("");
return (
<div>
<form>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Your Name"
/>
<p>{name}</p>
</form>
</div>
);
}
export default App;
//You will notice that we didn't create a function above the return statement to update the value of the state
```
## useEffect Hook
it carries out an effect each time there is a state change. By default, it runs after the first render and every time the state is updated.
**props.children**
```
<Profile>
<ProfileImage src="/asset/profile-img.png" />
<ProfileDetails name="Antonello" surname="Zanini" />
</Profile>
```
## using props
```
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
function App() {
return (
<div>
<Welcome name="Sara" />
<Welcome name="Cahal" />
<Welcome name="Edite" />
</div>
);
}
```
```
function formatDate(date) {
return date.toLocaleDateString();
}
function Comment(props) {
return (
<div className="Comment">
<div className="UserInfo">
<img className="Avatar"
src={props.author.avatarUrl}
alt={props.author.name} />
<div className="UserInfo-name">
{props.author.name}
</div>
</div>
<div className="Comment-text">
{props.text}
</div>
<div className="Comment-date">
{formatDate(props.date)}
</div>
</div>
);
}
const comment = {
date: new Date(),
text: 'I hope you enjoy learning React!',
author: {
name: 'Hello Kitty',
avatarUrl: 'http://placekitten.com/g/64/64'
}
};
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<Comment
date={comment.date}
text={comment.text}
author={comment.author} />
);
```
> All React components must act like pure functions with respect to their props.
active links when clickin on user
username
pass
phone number
email
### search
render works on result
result is updated
https://react-query-v3.tanstack.com/
or -> filter-data
---
## writing a clean code
1-project structure
src:
authprovider?? search it->on routing
context??
authcontext
usercontextc
usercrudcontext
-
# conditional rendering
### rendering components based on a specific condition using `if statements, &&, and ? : operators`
* make a function that will render the component if it was true
* make another function "a component" that will render the whole thing, we'll put the first function inside the second one.
```
function Item({ name, isPacked }) {
return <li className="item">{name}</li>;
}
export default function PackingList() {
return (
<section>
<h1>Sally Ride's Packing List</h1>
<ul>
<Item
isPacked={true}
name="Space suit"
/>
<Item
isPacked={true}
name="Helmet with a golden leaf"
/>
<Item
isPacked={false}
name="Photo of Tam"
/>
</ul>
</section>
);
}
```
here we have a function "item" that will return a list element if it was set to true
the other function will render a component that will show the li element if it was true, it'll hide it if it was false.
---
## node.js
#### refreshment
###### callback functions
a callback function is a function that is passed as an argument to another function and is executed after the completion of some asynchronous operation or upon some event occurring. The main purpose of a callback function is to ensure that certain code runs only after another piece of code has finished executing.
Callback functions are commonly used in JavaScript for tasks such as handling user input, making HTTP requests, or executing animations. They can also be used to simplify code and make it more modular by allowing developers to separate out certain tasks into separate functions.
```
function callbackFunction() {
console.log('This is a callback function');
}
function someFunction(callback) {
console.log('Do some stuff');
callback();
}
someFunction(callbackFunction);
```
###### promises
a Promise is an object that represents a value that may not be available yet, but will be resolved at some point in the future. Promises are used to handle asynchronous operations in JavaScript in a more elegant and maintainable way than using callbacks.
A Promise can be in one of three states:
Pending: The initial state, the Promise is neither fulfilled nor rejected.
Fulfilled: The Promise has been resolved successfully, and a value is available.
Rejected: The Promise has been rejected due to an error or failure.
Promises work by returning an object that has a then() method, which is called when the Promise is fulfilled or rejected. The then() method takes two callback functions as parameters: one for the fulfillment of the Promise, and one for the rejection. The Promise can be chained by returning another Promise from within the callback functions.
**syntax:**
```
const promise = new Promise((resolve, reject) => {
// async operation
// if successful, call resolve with value
// if error occurs, call reject with error
});
promise.then((result) => {
// handle successful result
}).catch((error) => {
// handle error
});
```
**chain multiple asynchronous operations together:**
```
function getUser(userId) {
return new Promise((resolve, reject) => {
// make API call to get user by ID
// if successful, call resolve with user object
// if error occurs, call reject with error
});
}
function getOrders(user) {
return new Promise((resolve, reject) => {
// make API call to get orders for user
// if successful, call resolve with orders array
// if error occurs, call reject with error
});
}
getUser(123)
.then((user) => {
return getOrders(user);
})
.then((orders) => {
console.log(orders); // log the orders array
})
.catch((error) => {
console.error(error); // log the error
});
```
##### ^two functions are defined that return Promises: getUser and getOrders. The then() method is used to chain the two Promises together: the getUser Promise is resolved with a user object, which is then passed as a parameter to the getOrders function. The getOrders Promise is then resolved with an array of orders, which is logged to the console. If any errors occur, they are caught and logged to the console.
___
---
# express.js
```
npx express-generator
npm install
DEBUG=myapp:* npm start
```
```
project structure :
.
├── app.js
├── bin
│ └── www
├── package.json
├── public
│ ├── images
│ ├── javascripts
│ └── stylesheets
│ └── style.css
├── routes
│ ├── index.js
│ └── users.js
└── views
├── error.pug
├── index.pug
└── layout.pug
7 directories, 9 files
```