route parameters react code example

Example 1: react router url params

import { Route, useParams } from "react-router-dom";

// Route with URL param of id
<Route path="/:id" children={<Child />} />

// We can use the `useParams` hook here to access
// the dynamic pieces of the URL.
let { id } = useParams();

Example 2: react js router parameters

// Declaramos la ruta
<Route path="/thanks/:status" component={ThanksPage} />
// Obtenemos la variable
import { useParams } from "react-router-dom";

const { status } = useParams();

Example 3: pass params react js

//pass color from parent -> child

App.js -> ColorPicker (Components/ColorPicker.js)

/// parent App.js
import ColorPicker from './Component/ColorPicker';

class App extends Component {
  
   constructor(props) {
        super(props);
        this.state = {
            color:  'red',
        };
    }
  
   render() {
        return (
			<div className="col">
    			<ColorPicker color={ this.state.color } />     
			</div>
		)
    }
}export default App;        

/// child ColorPicker
import React, { PureComponent } from 'react';

class ColorPicker extends PureComponent {  

    constructor(props) {
        super(props);
        this.state = {
            colors: ['red', 'green', 'blue', 'yellow', 'purple'],
        };
    }

    render() {

        var elementColors = this.state.colors.map((c, index) => {
            return <span key={ index } 
                         className={ this.props.color === c ? 'active squad ml-10' : 'squad ml-10'}
                        }  // click into color c will pass params c to Bai11Practice.js
                        >
                   </span>
        });
}
export default ColorPicker;    

// ---------------------------------------

//pass params from child -> parent
// onClick => setActiveColor -> this.props.onReceiverColor(c);
ColorPicker (Components/ColorPicker.js) -> App.js 

/// child ColorPicker
import React, { PureComponent } from 'react';

class ColorPicker extends PureComponent {  

    constructor(props) {
        super(props);
        this.state = {
            colors: ['red', 'green', 'blue', 'yellow', 'purple'],
        };
    }
  
    setActiveColor = (c)  => {
        this.props.onReceiverColor(c);
    }

    render() {

        var elementColors = this.state.colors.map((c, index) => {
            return <span key={ index } 
                        onClick={ () => this.setActiveColor(c) }  // click into color c will pass params c to Bai11Practice.js
                        >
                   </span>
        });
}
export default ColorPicker;        

// Parent
import React, { Component } from 'react';
import ColorPicker from './Component/ColorPicker';

class App extends Component {

    onSetColor(c) {
        alert(c);
    }

    render() {
        return (
		        <ColorPicker onReceiverColor={ this.onSetColor } />     
        );
    }
}export default App;