# React [Links](../../Export-9fad9947-5bd5-4195-952b-6512c5a4beb1/Web%20development%2083dd4e6675f04ba782a6865a434a0598/React%205b9af27e2c194a4cb22a32306e53c39f/Links%208668d1c86d604b9b8ea3d865e2e39428.md) - Forms of react for different devices react-dom : web browser react-native: mobile apps including android and ios react-nodegui: for desktop apps [React app to mobile app](../../Export-9fad9947-5bd5-4195-952b-6512c5a4beb1/Web%20development%2083dd4e6675f04ba782a6865a434a0598/React%205b9af27e2c194a4cb22a32306e53c39f/React%20app%20to%20mobile%20app%2016113733577b4d2cbcaf3f7241.md) [Creating react app to exe file](../../Export-9fad9947-5bd5-4195-952b-6512c5a4beb1/Web%20development%2083dd4e6675f04ba782a6865a434a0598/React%205b9af27e2c194a4cb22a32306e53c39f/Creating%20react%20app%20to%20exe%20file%209fd8b11fbb14409794a.md) - React-router-dom Creating structure for routes: ```jsx import { Route, Routes, Link, BrowserRouter as Router } from "react-router-dom"; const routing = ( } /> } /> ); ReactDOM.render( // routing, /* */ document.getElementById("root") ); // deleivering state to destination page: import {useNavigate} from 'react-router-dom'; const navigate = useNavigate(); navigate(`/Similar/${encodeURI(title)}`, { state: props, }); // getting state from destination page: import { useLocation } from "react-router-dom"; const { state } = useLocation(); const { poster_path, title, vote_average, overview, id } = state; ``` - No value dynamic attributes in React For attributes in jsx having no value like disabled in select element for eg: ```html ``` If we want the disabled due to be dynamic means it should be disabled on basis of given condition then ```jsx { func(e,arg1); }} ``` - Caution for storing component in state Its advisable to not store react component in state like ```jsx const [comp,setComp]= useState(null) setComp(Comp) ``` Here Comp is React component. Problem with this is when we try to pass setState hook or class method then setstate may not work as state may not store such complex things - Practical example showing importance of keys Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity: For eg: If we have list of child components having their own state which are rendered dynamically according to the data which can be changed due to events. If data is changed, suppose item is deleted so that particular component is deleted at position say 2. Then when re-rendering, component which was at position 3, will be in position 2. So now state of component which was in position 2, that state will be used as position is same. **Proof:** ```jsx import React from 'https://cdn.skypack.dev/react'; import ReactDOM from 'https://cdn.skypack.dev/react-dom'; const {useState} =React const Item=(props)=>{ const {item,setItems,items}=props const [qty,setQty]=useState(0) return(
{item}: {qty}
) } // key={item} const App = () => { const [items,setItems]=useState (['strawberry','apple','orange','grapes','pear']) const itemsarray=items.map((item)=>{ return( ) }) return (
{itemsarray}
); } ReactDOM.render(, document.getElementById("root")); ``` ![Untitled](../../_resources/Untitled-1.png) After deleting 1st item: ![Untitled](../../_resources/Untitled%201.png) As we can see state ‘qty’ dont get deleted as here component are identified only due to position. So we need to provide the key to uniquely identify them ```jsx import React from 'https://cdn.skypack.dev/react'; import ReactDOM from 'https://cdn.skypack.dev/react-dom'; const {useState} =React const Item=(props)=>{ const {item,setItems,items}=props const [qty,setQty]=useState(0) return(
{item}: {qty}
) } const App = () => { const [items,setItems]=useState (['strawberry','apple','orange','grapes','pear']) const itemsarray=items.map((item)=>{ return( ) }) return (
{itemsarray}
); } ReactDOM.render(, document.getElementById("root")); ``` ![Untitled](../../_resources/Untitled%202.png) After deleting ‘strawberry’: ![Untitled](../../_resources/Untitled%203.png) - render parent component when child state is changed. Normally when parent component is re-rendered, child component also get rendered. Proof: ```jsx import React from 'https://cdn.skypack.dev/react'; import ReactDOM from 'https://cdn.skypack.dev/react-dom'; // import {useState} from 'https://cdn.skypack.dev/react' const {useState} =React const Child=(props)=>{ const [state,setState]=useState(0) console.log('Child component rendered') return(
Child
) } const App = () => { const [state,setState]=useState(0) console.log('\nParent component rendered') return (
); } ReactDOM.render(, document.getElementById("root")); ``` ![Untitled](../../_resources/Untitled%204.png) To stop rerendering: use React.memo() while exporting child component in Child.js file ```jsx import React from "react"; function Child(props) { console.log("child component"); return
child Page
; } export default React.memo(Child); ``` When child component is updated then parent component is not updated as we can see from console output. So to update the parent component when child component is updated. If we want to rerender parent component for any child state changes then we can pass any state like render and setRender from parent to child and change that state in child component when child state changes thus updating parent component too. ```jsx const Child=({setRender,render})=>{ const [state,setState]=useState(0) useEffect(() => { setRender(render+1) }, [state]) console.log('Child component rendered') return(
Child
) } const App = () => { const [state,setState]=useState(0) const [render,setRender]=useState(0) console.log('\nParent component rendered') return (
); } ReactDOM.render(, document.getElementById("root")); ``` ![Untitled](../../_resources/Untitled%205.png) - Animation Tilt and Particles: ![Untitled](../../_resources/Untitled%206.png) For GUI testing in particles.js use: [https://vincentgarreau.com/particles.js/](https://vincentgarreau.com/particles.js/) - tippyjs ![Untitled](../../_resources/Untitled%207.png) ![Untitled](../../_resources/Untitled%208.png) - Equivalent of useEffect For eg: using useeffect: ```jsx import { useState, useEffect, Fragment } from "react"; import "./styles.css"; export default function App() { const [int, setInt] = useState(0); useEffect(()=>{ console.log(int) },[int]) const handleClick=()=>{ setInt(int+1) } return (

Hello CodeSandbox

Start editing to see some magic happen!

); } ``` same using componentDidUpdate() ```jsx import "./styles.css"; import {Component} from 'react' class App extends Component { constructor(){ super() this.state={ int: 0 } // this.handleClick=this.handleClick.bind(this) } handleClick=()=>{ this.setState({int: this.state.int+1}) // console.log(this.state.int) } componentDidMount(){ console.log(this.state.int) } // for checking props, prevProps is used instead of prevState componentDidUpdate(prevState){ if(this.state.int!==prevState.int){ console.log(this.state.int) } } render(){ return(

Hello CodeSandbox

Start editing to see some magic happen!

) } } export default App; ``` - bind() method [https://www.freecodecamp.org/news/this-is-why-we-need-to-bind-event-handlers-in-class-components-in-react-f7ea1a6f93eb/](https://www.freecodecamp.org/news/this-is-why-we-need-to-bind-event-handlers-in-class-components-in-react-f7ea1a6f93eb/) By default user defined methods in class components is not binded by default so we need to explicitly bind it. ```jsx class Foo extends React.Component{ constructor( props ){ super( props ); this.handleClick = this.handleClick.bind(this); } handleClick(event){ // your event handling logic } render(){ return ( ); } } ReactDOM.render( , document.getElementById("app") ); ``` if bind is not used then this.handleclick wont be available. - dispatch [dispatch() is the method used to dispatch actions](https://redux.js.org/api/store#dispatchaction)  and trigger state changes to the store. react-redux is simply trying to give you convenient access to it - Lifescycle of useeffect,usestate and useref First if any even changes state then state is changed causing component to re render so that new state value if used in DOM will be updated too Then after component is re render, side effects in useEffect take place if specified state in array(2nd parameter changes) Example to demonstrate: ```jsx import { useState, useEffect, useRef } from "react"; import ReactDOM from "react-dom/client"; function App() { const [inputValue, setInputValue] = useState(""); const previousInputValue = useRef(""); useEffect(() => { previousInputValue.current = inputValue; }, [inputValue]); return ( <> setInputValue(e.target.value)} />

Current Value: {inputValue}

Previous Value: {previousInputValue.current}

); } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(); /* Start typing in the input field and you will see the current- and previous value. */ ``` ![Untitled](../../_resources/Untitled%209.png) - Alternative of innerHTML in react [https://stackoverflow.com/questions/19266197/reactjs-convert-html-string-to-jsx](https://stackoverflow.com/questions/19266197/reactjs-convert-html-string-to-jsx) ```jsx import ReactHtmlParser from 'react-html-parser'
{ReactHtmlParser(htmlString)}
``` - Preventing propagation of event from parent to child [https://www.antimath.info/jquery/prevent-inner-elements-trigger-an-event-on-the-parent/](https://www.antimath.info/jquery/prevent-inner-elements-trigger-an-event-on-the-parent/) ```jsx $('#parent a').on('click', function(event){ //stop the event bubbling up to the parent event.stopPropagation(); }); $('#parent').on('click', function(event){ //attach event on the parent alert('Parent element clicked!'); }); ``` - Disabling eslint for specific piece of code ```jsx searchednotes.push(note); } setIsSearching(true); setSearchedNotes(searchednotes); }, [searchValue]); // eslint-disable-line react-hooks/exhaustive-deps ``` - React helmet - Creating and export/import text file in react ```jsx const download=()=>{ fetch(`${HOST}`,{ }) .then(res=>res.blob()) .then(blob=>{ const url = URL.createObjectURL(blob); const link = document.createElement("a"); link.download = "extraordinary12.mp3"; link.href = url; link.click(); }) .catch(console.log) } ``` [https://spin.atomicobject.com/2022/03/09/create-export-react-frontend/](https://spin.atomicobject.com/2022/03/09/create-export-react-frontend/) [https://spin.atomicobject.com/2022/03/09/create-export-react-frontend/](https://spin.atomicobject.com/2022/03/09/create-export-react-frontend/) [https://www.geeksforgeeks.org/how-to-read-a-local-text-file-using-javascript/](https://www.geeksforgeeks.org/how-to-read-a-local-text-file-using-javascript/) ```html Read Text File

          
        
    
      
    
    ```
    
    - Common mistakes
        
        [https://www.youtube.com/watch?v=Fhu5cu864ag](https://www.youtube.com/watch?v=Fhu5cu864ag)
        
        [https://www.youtube.com/watch?v=Fhu5cu864ag](https://www.youtube.com/watch?v=Fhu5cu864ag)
        

- image to dataURI
    
    [Extract data uri from image](../../Export-9fad9947-5bd5-4195-952b-6512c5a4beb1/Web%20development%2083dd4e6675f04ba782a6865a434a0598/React%205b9af27e2c194a4cb22a32306e53c39f/Extract%20data%20uri%20from%20image%205610c5f6df1b49978b3a19.md)
    
- Nodejs 17+ changes
    
    We need to add this in scripts section in package.json file:
    
    ```json
    "start": "react-scripts --openssl-legacy-provider start",
    "build": "react-scripts --openssl-legacy-provider build",
    ```
    
    the `--openssl-legacy-provider` flag is added as extra
    
- JoTai global state
    
    Instead of using useState and passing it in prop repeatedly, we can use it globally by calling the state from a file.
    
    atom.js
    
    ```jsx
    import { atom } from 'jotai'
    
    export const countAtom = atom(0)
    
    ```
    
    App.js
    
    ```jsx
    import { useAtom } from 'jotai'
    import {countAtom} from './atom'
    
    function Counter() {
      const [count, setCount] = useAtom(countAtom)
      return (
        

{count} ... ```