cover
ReactJavaScriptTypescript

Reactjs

Cover
https://cdn.iconscout.com/icon/free/png-512/free-react-4-1175110.png?f=webp&w=256
Slug
ReactJS
Published
Published
Date
Jan 14, 2024
Category
React
JavaScript
Typescript

Props

import PropTypes from 'prop-types' function Navbar(props) { return ( <nav className="navbar navbar-expand-lg navbar-light bg-light"> <a className="navbar-brand" href="/">{props.title}</a> ); }
Navbar.prototype = { title: PropTypes.string, aboutText: PropTypes.string } //default props Navbar.defaultProps = { title: "set title", aboutText: "set aboutText" }
Navbar.js
 
function App() { return ( <> <Navbar title = "Shiv" aboutText = "About Shiv"/> </> ); }
App.js
💡
(alias) type ReactNode = string | number | boolean | ReactElement<any, string | JSXElementConstructor<any>> | Iterable<ReactNode> | ReactPortal | PromiseLikeOfReactNode | null | undefined
import ReactNode

State & Handling Events (React Hooks)

import React, { useState } from 'react'; function Example() { // Declare a new state variable, which we'll call "count" // setCount function const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); }

React Router

import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
<Router> <Navbar title = "Shiv" aboutText = "About" mode = {mode} toggleMode = {toggleMode} /> <Alert alert = {alert}/> <div className="container my-4"> <Routes> <Route exact path="/" element={<TextForm heading="Enter the text to analyze below" mode={mode} showAlert={showAlert} />} /> <Route exact path="/about" element={<About mode={mode} />} /> </Routes> </div> </Router>

React Hooks

Features of class based components hooks into function
  • useState
  • useEffect
  • useContext
  • useRef
  • useLocation
 

Context API

The React Context API is a way to share state between components without having to pass props down through the component tree. This can be useful for sharing data that is needed by many components, such as the current user or the current theme.
To use the Context API, you first need to create a context object. This can be done using the createContext() function. The context object will store the data that you want to share.
Once you have created a context object, you can provide it to any component in your app using the Provider component. The Provider component will make the context data available to all of its child components.
To access the context data in a child component, you can use the useContext() hook. The useContext() hook will return the context data for the current context.
import { createContext } from "react"; const NoteContext = createContext(); export default NoteContext;
NoteContext.js
import { useState } from "react"; import NoteContext from "./NoteContext"; export default function NoteState(props) { const s1 = { "name": "Shiv", "class": "5A", } const [state, setState] = useState(s1); const update = () => { setTimeout(() => { setState({ "name": "Shiv", "class": "NFSU", }) } , 2000); } return ( <NoteContext.Provider value={{state:state, update:update}}> {props.children} </NoteContext.Provider> ) }
NoteState.js
import React, { useEffect } from 'react'; import { useContext } from 'react'; import NodeContext from '../context/notes/NoteContext'; export default function About() { const note = useContext(NodeContext); useEffect(() => { note.update(); // eslint-disable-next-line }, []); return ( <div> This is {note.state.name} {note.state.class} </div> ); }
About.js
<NoteState> <Router> <Navbar title = "Shiv" aboutText = "About" /> <Routes> <Route exact path="/" element={<Home/>} /> <Route exact path="/about" element={<About />} /> </Routes> </Router> </NoteState>
App.js
 

useLocation Hook

let location = useLocation(); useEffect(() => { console.log(location.pathname); // ga.send(['pageview', location.pathname + location.search]); }, [location]);
 

Use ref

it is an object that used to access a DOM element directly
its never re render element , just store current state of element
import { useRef } from 'react'; export default function Counter() { let ref = useRef(0); function handleClick() { ref.current = ref.current + 1; alert('You clicked ' + ref.current + ' times!'); } return ( <button onClick={handleClick}> Click me! </button> ); }

Lists & Key

Key - A string attribute that identifies items in lists of elements.
function NumberList(props) { const numbers = props.numbers; const listItems = numbers.map((number) => <li key={number.toString()}> {number} </li>); return ( <ul>{listItems}</ul>); }
const todoItems = todos.map((todo) => <li key={todo.id}> {todo.text} </li>);
Key & value
function ListItem(props) { const value = props.value; return ( // Wrong! There is no need to specify the key here: <li key={value.toString()}> {value} </li>); } function NumberList(props) { const numbers = props.numbers; const listItems = numbers.map((number) => // Wrong! The key should have been specified here: <ListItem value={number} /> ); return ( <ul> {listItems} </ul>); }
 

Important

export default function Projects() { return ( <section> <SectionHeading>My projects</SectionHeading> <div> {projectsData.map((project, index) => ( <React.Fragment key={index}> <Project {...project} /> </React.Fragment> ))} </div> </section> ); } type ProjectProps = (typeof projectsData)[number]; function Project({ title, description, tags, imageUrl }: ProjectProps) { return ( <div> {title} </div> ); }
  • <React.Fragment> component is used as a wrapper to group multiple elements together without adding an extra DOM element.
  • The key prop is used to uniquely identify each element in the list, which is important for React to efficiently update the list when changes occur.
  • The <Project {...Project}/> component is likely rendering a single project based on the data provided in the Project object.
  • The spread operator (...) is used to pass all the properties of the Project object as separate props to the <Project> component.

react-intersection-observer

The react-intersection-observer package is a React implementation of the Intersection Observer API. It provides a way to monitor the visibility of different sections on a webpage and dynamically execute actions on the page header. The package has three main implementations: Hooks, render props, and plain children.
npm install react-intersection-observer --save
import React from 'react'; import { useInView } from 'react-intersection-observer'; const Component = () => { const { ref, inView, entry } = useInView({ /* Optional options */ threshold: 0, }); return ( <div ref={ref}> <h2>{`Header inside viewport ${inView}.`}</h2> </div> ); };
 

Related Posts