I'm having problems using history.push("path/...") within a function component. My problem is when i try to use a function component's param in the button handler. I have the next code:
Example.js
...
import {useHistory} from 'react-router-dom';
...
//This function works fine, but i would prefer something reusable
function Button() {
const history = useHistory();
function handle(){
history.push("/path"); //The path is harcoded
}
return(
<button onClick={handle}>
Home //This text is harcoded
</button>
);
}
//This is what i'm looking for, because i would write it once.
function Button(path, text) {
const history = useHistory();
function handle(){
history.push(path); //This doesn't work
}
return(
<button onClick={handle}>
{text} //This throws an error "no valid react child"
</button>
);
}
//this component is being render as a child of BrowserRouter
class Example extends Component{
render(){
return(
<div>
<Button path="path/..."/>
</div>
);
}
}
export ...
This is my actual code, just removed repeated lines. With the first function component i have no problems, but, I'm in the need to create a new function component for every button. Instead i'm looking for a way to write this functions once and use it to create many buttons.
The second function does nothing when the path is being passed through props, and if I add console.log(path) in the handle(), the path value is printed as it is passing correctly, but history.push(path) does not take it.
I want to add that, the only clue I have is the push method documents, where the types this method takes are string, but any is being passed.
React components receive only a single argument that is the props object. You are assuming two.
function Button(path, text) {
const history = useHistory();
function handle(){
history.push(path); // This doesn't work
}
return(
<button onClick={handle}>
{text} // This throws an error "no valid react child"
</button>
);
}
should be
function Button({ path, text }) {
const history = useHistory();
function handle(){
history.push(path); // This should work now
}
return(
<button onClick={handle}>
{text} // This should render now
</button>
);
}
Notice here the passed props are destructured from the props object.
Send path and name as props and use those inside your button function.
<Button path="path/..."/ name="Home">
function Button({path,name}) {
const history = useHistory();
function handle(){
history.push(path);
}
return(
<button onClick={handle}>
{name}
</button>
);
}