Reputation: 111
The ButtonList
returns a list of filtered Buttons
that should each link to a new page. I would like to do it by adding dynamic routes, but I don't know how to write the code... How do I use history.push correctly? Any help would be highly appreciated.
export default function Home() {
const [searchValue, setSearchValue] = useState("");
const history = useHistory();
const filteredData = data.filter(item =>
item.name.toLowerCase().includes(searchValue.toLowerCase())
);
function handleSearch(value) {
setSearchValue(value);
}
const selectedItem = filteredData.find(item => item.name);
function handleSelect(item) {
history.push(`/home/${item.name}`);
}
return (
<WrapperDiv>
<StyledHeader />
<Switch>
<Route exact path="/home">
<Searchbar onSearch={handleSearch} />
<ButtonList data={filteredData} onClick={handleSelect} />
</Route>
<Route exact path="/home/{...}">
<StyledDiv>
<Button item={selectedItem} light />
<AccordionList />
</StyledDiv>
</Route>
</Switch>
</WrapperDiv>
);
}
export default function Button({ children, handleSelect }) {
return (
<button
to={{
pathname: "/home/" + data.name,
data: data
}}
onClick={handleSelect}
>
{children}
</button>
);
}
export const data = [
{
name: "Apple",
id: 1
},
{
name: "Banana",
id: 2
},
{
name: "Blueberry",
id: 3
}
];
Upvotes: 0
Views: 57
Reputation: 159
one good way to achieve it would be to use React Router which makes creating dynamic routes really easy.
Writing the whole code is a little difficult here, therefore I found a good example of an easy way to implement react-router with your code.
Example
import { useHistory } from "react-router-dom";
function MyButton() {
let history = useHistory();
function triggerClick() {
history.push("/somewhere");
}
return (
<button type="button" onClick={triggerClick}>
Go somewhere
</button>
);
}
Upvotes: 1