React Merged
React Merged
React Merged
Introduction to React
Table of Content
1. What is React?
2. JSX Syntax
3. Rendering Elements
4. React Components
1. What is React?
React is a JavaScript library created by Facebook for building user interfaces. React is
used to build single-page applications. React allows us to create reusable UI
components.
3. Move to the Directory where you want to create your react application. Open
Command prompt / Terminal and use this npx command. (npx is not a typo)
JSX allows us to write HTML elements in JavaScript and place them in the DOM without
any createElement() and/or appendChild() methods. JSX converts HTML tags into react
elements.
JSX is an extension of the JavaScript language based on ES6, and is translated into
regular JavaScript at runtime.
const myElement = (
<ul>
<li>Apples</li>
<li>Bananas</li>
<li>Cherries</li>
</ul>
);
Expressions in JSX {}
With JSX you can write expressions inside curly braces { } .
The expression can be a React variable, or property, or any other valid JavaScript
expression. JSX will execute the expression and return the result:
Conditions - if statements
React supports if statements, but not inside JSX. Because the if statements are
not expressions in Javascript. You could use a ternary expression instead:
const x = 5;
CSS Styling
You can use Inline Styling or a StyleSheet to style your elements in React.
1. Inline Styling
In JSX, JavaScript expressions are written inside curly braces, and since
JavaScript objects also use curly braces, the styling in the example above is
written inside two sets of curly braces {{}}
You can also create an object with styling information, and refer to it in the style
attribute:
const myStyle = {
color: "white",
backgroundColor: "DodgerBlue",
padding: "10px",
fontFamily: "Sans-Serif"
2. CSS Stylesheet
You can write your CSS styling in a separate file, just save the file with
the .css file extension, and import it into your application.
import './App.css';
3. Rendering Elements
Elements are the smallest building blocks of React apps.
Unlike browser DOM elements, React elements are plain objects, and are cheap to
create. React DOM takes care of updating the DOM to match the React elements.
Applications built with just React usually have a single root DOM node. To render a
React element, first pass the DOM element to ReactDOM.createRoot(), then pass
the React element to root.render():
With our knowledge so far, the only way to update the UI is to create a new
element, and pass it to root.render() .
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
2. Class Components
You can also use an ES6 class to define a component:
The above two components are equivalent from React’s point of view.
Composing Components
Components can refer to other components in their output. This lets us use the
same component abstraction for any level of detail. A button, a form, a dialog, a
screen: in React apps, all those are commonly expressed as components.
For example, we can create an App component that renders Welcome many times:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
function App() {
return (
<div>
<Welcome name="Sara" />
<Welcome name="Cahal" />
Browsers don’t understand JSX out of the box, so most React users rely on a
compiler like Babel or TypeScript to transform JSX code into regular JavaScript.
Many preconfigured toolkits like Create React App or Next.js also include a JSX
transform under the hood.
For example, let’s say your source code looks like this:
function App() {
return <h1>Hello World</h1>;
}
Under the hood, the old JSX transform turns it into regular JavaScript:
function App() {
return React.createElement('h1', null, 'Hello world');
}
Assignment
1. Build an accordion component to display FAQs.
2. Build a clone of YouTube video page section. Create Different components for all
the red boxes.
Table of Content
1. React states
3. Events Handling
4. Lists in React
1. React states
The state is a built-in React object that contains data or information about
the component.
A component’s state can change over time; whenever it changes, the component re-
renders. The change in state can happen as a response to user action or system-
generated events and these changes determine the component's behavior and how it
will render.
initialise state
We initialize our state by calling useState in our function component.
useState accepts an initial state and returns two values:
function FavoriteColor() {
const [color, setColor] = useState("");
The [ and ] syntax here is called array destructuring and it lets you read values from
an array. The array returned by useState always has exactly two items.
update state
To update our state, we use our state updater function.
We should never directly update state. Ex: color = "red" is not allowed.
<button
onClick={() => setColor("blue")}>
Blue
</button>To update the state based on the previous state, use this format instead:
You can use an object that includes the all 4 properties, like this:
But,
If we only called setCar({color: "blue"}) , this would remove the brand, model, and
year from our state.
setCar(previousState => {
return { ...previousState, color: "blue" }
});
1. Define a callback in the parent which takes the data you need in as a parameter.
3. Call the callback using props.[callback] in the child (insert your own name where it
says [callback] of course), and pass in the data as the argument.
3. Event Handling
React lets you add event handlers to your JSX. Event handlers are your own functions
that will be triggered in response to user interactions like clicking, hovering, focusing on
form inputs, and so on.
Built-in components like <button> only support built-in browser events like onClick .
However, you can also create your own components, and give their event handler props
any application-specific names that you like.
4. Lists in React
In React, you will render lists with some type of loop. The JavaScript map() array
method is generally the preferred method.
If cars.length > 0 is equates to true, the expression after && will render.
You should pass the key attribute which should be unique to every list element.
Assignments
1. Create a Unit Converter Application
https://s3-us-west-2.amazonaws.com/secure.notion-static.com/c8bc19a6-02
c0-458c-a63d-93e11c753497/Screen_Recording_2022-12-07_at_8.47.10_P
M.mov
2. Create a Notes Taking App with the following UI. Here you use the green card to
create new Notes. Add the functionality to filter the Notes by typing to search.
Table of Content
1. User Input Forms
3. React Hooks
function handleChange(event) {
setInputValue(event.target.value);
}
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={inputValue} onChange={handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
Since the value attribute is set on our form element, the displayed value will always
be this.state.value, making the React state the source of truth. Since handleChange
runs on every keystroke to update the React state, the displayed value will update
as the user types.
useEffect Hook
The Effect Hook lets you perform side effects in function components. • We can use
mount and unmount behavior in React hooks to run code at specific lifecycle times
in the component.
1. pass nothing:
useEffect(() => {
console.log("useEffect has been called!", button);
});
useEffect(() => {
console.log("useEffect has been called!", button);
}, []);
useEffect(() => {
console.log("useEffect has been called!", button);
}, [inputText]);
Runs when the component mounts and the elements inside the array change.
useEffect(() => {
console.log("Use Effect!")
return () => {
console.log("Unmount")
}
})
3. React Hooks
React provides a few built-in Hooks like useState . You can also create your own Hooks
to reuse stateful behavior between different components.
Hooks are JavaScript functions, but they impose two additional rules:
Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or
nested functions.
Only call Hooks from React function components. Don’t call Hooks from regular
JavaScript functions.
useRef hook
useRef is a React Hook that lets you reference a value that’s not needed for
rendering.
function Stopwatch() {
const intervalRef = useRef(0);
// ...
useRef returns a ref object with a single current property initially set to the initial
value you provided.
Changing a ref does not trigger a re-render. This means refs are perfect for
storing information that doesn’t affect the visual output of your component.
You can store information between re-renders (unlike regular variables, which
reset on every render).
The information is local to each copy of your component (unlike the variables
outside, which are shared).
💡 You mostly use the useRef hook to store the reference to the dom
elements to read certain properties out of the dom element.
Assignments
1. In the News Application, add a List of Topics for the user to select from and then
show the result based on the selected item.
Table of Content
1. Basics of React-Router-Dom
3. Protected Routes
BrowserRouter
First, you'll need to set up your app to work with React Router. Everything that gets
rendered will need to go inside the <BrowserRouter> element, so wrap your App in
those first. It's the component that does all the logic of displaying various
components that you provide it with.
// index.js
ReactDOM.render(
<BrowserRouter>
<App />
Route
Put simply, Route allows you to map your app's location to different React
components. For example, say we wanted to render a Dashboard component
whenever a user navigated to the /dashboard path. To do so, we'd render
a Route that looked like this.
<Route
path="/dashboard"
element={<Dashboard />}
/>
The mental model I use for Route is that it always has to render something – either
its element prop if the path matches the app's current location or null , if it doesn't.
You can render as many Route s as you'd like.
Routes
You can think of Routes as the metaphorical conductor of your routes. Whenever
you have one or more Route s, you'll most likely want to wrap them in a Routes .
function App() {
return (
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/settings" element={<Settings />} />
<Route path="*" element={<NotFound />} />
The reason for this is because it's Routes job is to understand all of its children
Route elements, and intelligently choose which ones are the best to render.
Link
Now that you know how to map the app's location to certain React components
using Routes and Route , the next step is being able to navigate between them. This
is the purpose of the Link component.
To tell Link what path to take the user to when clicked, you pass it a to prop.
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Link to="/settings">Settings</Link>
</nav>
Anytime you pass data along via the state prop, that data will be available on
the location 's state property, which you can get access to by using the
custom useLocation Hook that comes with React Router.
URL Parameters
Like function parameters allow you to declare placeholders when you define a
function, URL Parameters allow you to declare placeholders for portions of a URL.
e.g.:
<Route path="/wiki/:topicId" element={<Article />} />
Now whenever anyone visits a URL that matches the /wiki/:topicId pattern
( /wiki/javascript , /wiki/Brendan_Eich , /wiki/anything ) , the Article component is
rendered.
As of v5.1, React Router comes with a useParams Hook that returns an object with a
mapping between the URL parameter(s) and its value.
function Article () {
const [article, setArticle] = React.useState(null)
const { topicId } = useParams()
React.useEffect(() => {
getArticle(topicId)
.then(setUser)
}, [topicId])
return (
...
)
}
Nested Routes allow the parent Route to act as a wrapper and control the rendering
of a child Route.
function App() {
return (
<Routes>
<Route path="/" element={<Home />} />
<Route path="/messages" element={<Messages />}>
<Route path=":id" element={<Chats />} />
</Route>
<Route path="/settings" element={<Settings />} />
</Routes>
);
}
Now, tell React Router where in the parent Route ( Messages ) should it render the
child Route ( Chats ).
function Messages() {
return (
<Container>
<Conversations />
<Outlet />
</Container>
);
}
I
If the app's location matches the nested Route 's path , this Outlet component will
render the Route 's element . So based on our Routes above, if we were at /messages ,
the Outlet component would render null , but if we were at /messages/1 , it would
render the <Chats /> component.
Programmatically Navigate
To get access to the imperative navigate method, you'll need to use React
Router's useNavigate Hook. From there, you can pass navigate the new path you'd
like the user to be taken to when navigate is invoked.
function Register () {
const navigate = useNavigate()
return (
<div>
<h1>Register</h1>
<Form afterSubmit={() => navigate('/dashboard')} />
</div>
)
}
3. Protected Routes
Private Routes in React Router (also called Protected Routes) require a user being
authorized to visit a route (read: page). So if a user is not authorized for a specific page,
they cannot access it.
function ProtectedRoutes() {
const isLoggedIn = false;
return {isLoggedIn ? <Outlet/> : <Navigate to="/login" replace />};
}
Now, you can surround any Routes inside the ProtectedRoutes Component.
Further readings:
Assignments
1. Build a Platform with Login and Logout Functionalities. (Use State variables to store
the authentication data)
2. Create a website with navbar to toggle in between multiple pages. Also add a
TabLayout in one of the pages to toggle between multiple layouts. like this:
3. List all the recipes using this API and open each one separately on click in a
separate component.: https://spoonacular.com/food-api/docs
Table of Content
1. Introduction to Redux with React
4. Advantages of Redux
Thus, with Redux, it becomes clear where the components get their state from as well
as where should they send their states to. Now the component initiating the change
does not have to worry about the list of components needing the state change and can
simply dispatch the change to the store. This is how Redux makes the data flow easier.
ACTION: An object setting up information about our data moving into state.
STATE: Where all the data from our reducers are passed into a central source.
Store Once we have our Actions and Reducers set up everything is maintained in our
Store. The Store is where we can set up our initial state, combine our reducers, apply
middleware and hold our information.
Provider We can then use the Provider to wrap our store around our application and by
doing so pass and render our state. We *can then use Connect *with a component and
enabling it to receive Store state from the Provider.
const initialState = {
value: 0,
}
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
Now we can use the React-Redux hooks to let React components interact with the
Redux We can dispatch actions using useDispatch
return (
<div>
<div>
<button
onClick={() => dispatch(increment())}
>
Increment
</button>
<button
onClick={() => dispatch(decrement())}
>
Decrement
</button>
</div>
</div>
)
}
return (
<div>
<div>
<span>{count}</span>
</div>
</div>
)
}
4. Advantages of Redux
Following are some of the major advantages of Redux:
Predictability of outcome – Since there is always one source of truth, i.e. the
store, there is no confusion about how to sync the current state with actions and
other parts of the application.
Developer tools – From actions to state changes, developers can track everything
going on in the application in real time.
Ease of testing – Redux code are mostly functions which are small, pure and
isolated. This makes the code testable and independent.
Organization – Redux is very precise about how the code should be organized, this
makes the code more consistent and easier when a team works with it.
Assignments
2. Create a Login page and store the user information inside the redux store, display
the information inside the profile page using React Redux.
3. Create a cart app, where you can create new cart item along with the counter to
increment and decrement the quantities of the items. Inside the Navbar component,
display the total amount of items and total cart amount using React Redux
Table of Content
1. Using Middleware with Redux
2. Redux Thunk
Execute extra logic when any action is dispatched (such as logging the action and state)
Teach dispatch how to accept other values besides plain action objects, such as functions and promises, by
intercepting them and dispatching real action objects instead
https://d33wubrfki0l68.cloudfront.net/08d01ed85246d3ece01963408572f3f6dfb49d41/4bc12/assets/images/reduxasyncdataflowdiagram-
d97ff38a0f4da0f327163170ccc13e80.gif
2. Redux Thunk
Redux Toolkit's configureStore function automatically sets up the thunk middleware by default, and it is recommend
using thunks as the standard approach for writing async logic with Redux.
const initialState = {
posts: [],
status: 'idle',
error: null
}
and now inside the createSlice() method, we can use like this: