Hey folks! I’m working on upgrading my Laravel CRUD app with a React frontend. I’m pretty new to React and could use some guidance.
I’ve got a basic table component showing all users, but I’m not sure how to handle routing for individual user pages, create forms, and edit pages. What’s the best way to use React Router (or something similar) to swap out the user table with these other views when I click buttons like “show user”?
Also, I’m wondering about the best way to pass data from my Laravel backend to the React components. Any tips on that would be awesome!
Here’s a simplified version of what I’ve got so far:
import React from 'react';
import { BrowserRouter, Route, Link } from 'react-router-dom';
const UserList = ({ users, filterText }) => {
const filteredUsers = users.filter(user =>
user.name.toLowerCase().includes(filterText.toLowerCase()) ||
user.email.toLowerCase().includes(filterText.toLowerCase())
);
return (
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{filteredUsers.map(user => (
<tr key={user.id}>
<td>{user.name}</td>
<td>{user.email}</td>
<td>
<Link to={`/users/${user.id}`}>View</Link>
<Link to={`/users/${user.id}/edit`}>Edit</Link>
</td>
</tr>
))}
</tbody>
</table>
);
};
const App = () => {
const [users, setUsers] = React.useState([]);
const [filterText, setFilterText] = React.useState('');
React.useEffect(() => {
// Fetch users from API
}, []);
return (
<BrowserRouter>
<nav>
<Link to="/users">All Users</Link>
<Link to="/users/create">Create User</Link>
<input
type="text"
placeholder="Search..."
value={filterText}
onChange={(e) => setFilterText(e.target.value)}
/>
</nav>
<Route exact path="/users" render={() => <UserList users={users} filterText={filterText} />} />
{/* Add routes for other views */}
</BrowserRouter>
);
};
export default App;
Any help would be much appreciated! Thanks!