Thursday, December 31, 2020

Send user to a new url with parameter using React

Here is the scenario - You need update the page view when a user makes a selection from a drop down. Example: There is a drop down of employees and when the user makes a selection, you need to change the employee profile view to the selected employee.

First, you can pass a url parameter like so:   /yourUrl/2202.

You then read the parameter in the code like so: props.match.params.id

EX:     

let emp_id = {
      emp_id: props.match.params.id,
    };


SIDE NOTE: You will need to add match to propTypes and you do that like so:

  match: PropTypes.shape({
    params: PropTypes.shape({
      id: PropTypes.string,
    }),
  })

You also need to pass it in App.js like so: 

<Route path="/yourUrl/:id" component={YourComponent} />

Now that you have passed in your parameter, you can use it to get the employee info from the database. In this case, I am using useEffect. I create an argument from the ID passed in (see green text below) and then I pass the emp_id into my function to get the data for the employee (see blue text below). The red text below will call this function only if the ID has changed.

  useEffect(() => {

    let emp_id = {
      emp_id: props.match.params.id,
    };

    props.loadEmployee(emp_id);
  

  }, [props.match.params.id]);


Ok so now, lets add in a select function so the user can change the employee.

Simply add a select drop down like so:

<ValidationForm onSubmit={handleSubmit}>
<SelectGroup
  name="emp_id"
  id="emp_id"
  value={props.match.params.id}
  onChange={handleEmployeeChange.bind(this)}
>
  <option value=""></option>
  {props.employees.map((e, key) => {
return (
  <option key={key} value={e.employee_emp_id}>
{e.employee_name} ({e.employee_emp_id})
  </option>
);
  })}
</SelectGroup>
  </ValidationForm>

Ok let's walk through this code. 
  1. The blue line defaults the selection to the current url param.
  2. The red line handles the change
  3. The orange lines populate the drop down
Now, the red line calls another function and binds the selected employee ID. When the user makes a selection, here is the handleEmployeeChange function that is called:

 const handleEmployeeChange = (event) => {
    props.history.push(`/yourUrl/${event.target.value}`);
  };


handleEmployeeChange takes the selected value and calls the url which will load the data of the newly selected employee.

SIDE NOTE:  You can learn more about props.history.push here

That's it!

Let me know if you have any questions or suggestion of a better way!