So I am mapping over an array of users, and each user has a unique ID. I am wanting to create a path for the link which will include the unique ID of the user, depending on which link is clicked. Here is what I have tried so far (Link does not allow me to use template literals for some reason)
import React, {useEffect, useState} from 'react';
//import {axiosWithAuth} from '../api/axiosWithAuth';
//import axios from 'axios';
import {connect} from 'react-redux';
import {useParams, Link} from 'react-router-dom';
import {fetchUsers} from '../actions/index';
//get request to /api/users -- will return array of users
const ListUsers = props =>{
const [data, setData] = useState([{username:'hello world!'}]);
const params = useParams();
const path = `/Profile/${params.id}`
// function myFunction(id) {
// alert(item.id);
// }
useEffect(() => {
props.fetchUsers();
}, [])
return(
<div>
{props.users.map(item=>{return(
<Link path='/Profile' params={{id: item.id}}>
<div className="UsersCard">Username: {item.username} <br /> Name: {item.firstName} <br /> ID: {item.id} <br /> Email: {item.email} </div>
</Link>
)})}
</div>
)
}
const mapStateToProps = state => {
return {
users: state.users,
user: {},
registerSuccessMessage: '',
user_stories: {},
isLoading: false,
error: null
}
}
export default connect(mapStateToProps, {fetchUsers})(ListUsers);
//get request to /api/users/:id -- will return users specified by ID
Here is my routes
import React from 'react';
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import PrivateRoute from './api/PrivateRoute';
import SignIn from './Components/SignIn';
import SignUp from "./Components/SignUp";
import Profile from './Components/Profile';
import Stories from './Components/Stories';
import Nav from "./Components/Nav";
import ListUsers from './Components/ListUsers';
import EditUser from './Components/EditUser';
function App() {
return (
<div className="App">
<Router>
<Nav/>
<Switch>
<Route path='/SignIn' component={SignIn} />
<Route path='/SignUp' component={SignUp} />
<Route exact path='/' />
<PrivateRoute path='/UsersList' component={ListUsers} />
<PrivateRoute exact path='/Profile/:id' component={Profile} />
<PrivateRoute path='/Stories' component={Stories} />
<PrivateRoute path='/Profile/:id/editProfile' component={EditUser} />
</Switch>
</Router>
</div>
);
}
export default App;
I want it to take me to the '/Profile/:id' route according to whichever user is clicked
<Link to={`/Profile/${item.id}`}>
...
</Link>
For search params you can pass an object.
<Link to={{
pathname: "/Profile",
search: "?key=value",
}}>
...
</Link>