React reminders

Solution of the vehicles dealer

A solution of the project is available in https://github.com/tabary/vehiclesDealer

Foundations of JSX

Javascript expressions (such as constants, variables, or function calls) can be put inside JSX code by using curly braces. Here is an example:

 
function Example() {
    const text = "Hello world!"
    return (
      <p> {text} </p>
    )
}

It is important to note that one can also extract data coming from a JavaScript object:

 
function Example() {
    const quote = {text: "Hello world!", author: "me"};
    return (
      <p>
        <i>{quote.text}</i>
        written by
        <i>{quote.author}</i>
      </p>
    )
}    

Create a react application

  • cd ecoal25
  • npm create vite@latest client
    • select react
    • select Javascript + SWC
  • cd client
  • npm install axios react-router-dom
  • npm run dev : open the browser http://localhost:5173

Components

 
function Hello() {
    return (
        <div>
            Hello!!
        </div>
    )
}

export default Hello

Call a component

 
import Hello from './Hello.jsx'

function App() {
  return (
    <div>
      <Hello />
    </div>
  )
}

Pass data to componnents: that's props

 
// use { } to in order to display variable
function Hello(props) {
    return (
        <div>
            Hello {props.name}!!
        </div>
    )
}



function App() {
    return (
        <div>
            <Hello name='Gilles'/>
            <Hello name='Joao'/>
            <Hello name='Derek'/>
        </div>
    )
}

Do not duplicate code, use map!

 
let names = ['Gilles', 'Joao', 'Derek'];
function App() {
    return (
        <div>
            {names.map( n => <Hello name={n} />)}
        </div>
    )
}

States

 
import { useState } from 'react';

function App() {


    const [nb, setNb ] = useState(0)  // 0 is the initial value of the state

    function callMe() {
        setNb(nb+1) // Each time the function set Nb is called, the component is rendered again
    }

    return (
        <div>
        You click {nb} times on the button
        <button onClick={e => callMe()}>Click!</button>
        </div>
    )
}

Get data from server

You need to use the hook useEffect to this end. This hook is called each time the function is rendered again

 
import { useEffect } from 'react' // At the begining of the file

function Articles() {

...

let [articles, setArticles] = useState([]) // At the begining we do not have articles

async function getArticles() {  // The function is asynchronous
  const articles = (await axios.get('http://localhost:8000/articles')).data
  setArticles(articles)
}

useEffect(() => { // this is a hook called everytime the function is rendered again
                  // Don't forget to import useEffect
  getArticles()
}, [])

...


How to manage client routes

Client routes are very useful. With such routes, the client can benefit from a browser history and can for example load a specific page for each item from a collection. To deal with client routes, you have to install react-router-dom in your application using npm install react-router-dom. You also have to modify index.js and App.js as follows.
main.jsx
 
//....
import {BrowserRouter} from 'react-router-dom';

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </StrictMode>,
)
App.jsx
 
import {Route, Link, Routes} from "react-router-dom"
import Home from "./components/Home.jsx"
import Articles from "./components/Articles.jsx"

function App() {
return (
<>
<nav>
  <Link to="/">Home</Link>
  <Link to="/articles">News</Link>
</nav>

<Routes>
  <Route path="/" element={<Home/>} />
  <Route ="/articles" element={<Articles/>}/>
  <Route path="*" element={<p>Page Not Found</p>} />
</Routes>
</>
);
}

export default App
Assuming that your server is run on your computer, and the port is 5173, here are the two possible routes:
  • 127.0.0.1:5173
  • 127.0.0.1:5173/articles

Both components Home and Articles are rendered inside the main div.

How to create links to client routes

Do not use the tag a. Instead, use the component Link:

 
import {Link} from 'react-router-dom' // WARNING DO NOT FORGET :)!!

<Link  to={'/about'}>About page</Link>

How to create parameterized routes

It is sometimes useful to have a route while using a specific parameter. For example, in order to display all information concerning a given article, you can add a route like this:

 
<Route path="/article/:id" element={<Article/>}/>

Importantly, in order to get the value of the specified id in the component Article, follow this piece of code

 
import {useParams} from 'react-router-dom'

function Component() {
...

let params = useParams()
let id = params.id // Now you can use the id
...
}

How to do a redirection

 
import {useNavigate} from 'react-router-dom''

function MyComponent(props) {
    const navigate = useNavigate()

    if(IWantToMakeARedirection)
        navigate('/')