I would like to let users to move main component after they create content and I don't what methods I need to use. I wanted to use something like history but it didn't work. I am using
import React, { Component } from 'react';
class CreateContent extends Component {
constructor(props) {
super(props);
this.state = {
content: {
title: ''
}
}
}
handleInput = (e) => {
this.setState({
content : {
...this.state.content,
[e.target.name]: e.target.value
}
})
}
addContent = async (e) => {
e.preventDefault();
console.log(JSON.stringify(this.state.title))
try {
const response = await fetch('http://localhost:9000/api/v1/content', {
method: 'POST',
body: JSON.stringify(this.state.content),
mode:'cors',
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
}
});
if(!response.ok) {
throw Error(response.statusText)
}
// ******* HERE I wanted to add something like *******
history.push('/main')
} catch (err) {
console.log('addContent failed -', err)
}
}
render() {
return (
<div>
<form onSubmit={this.addContent}>
<input
type="text"
name="title"
onChange={this.handleInput}
value={this.state.content.title}
/>
<input type="submit" value="submit" />
</form>
</div>
)
}
}
export default CreateContent
In React Router v6
, you need to use useNavigate instead of history.push().
But, since you're using class component React Router v6
it doesn't support these hooks out of the box for the class components. That is why you are receiving the error:
Error: Invalid hook call. Hooks can only be called inside of the body of a function component.
But that doesn't mean you can't use it. You can recreate it using HOC:
import {
useLocation,
useNavigate,
useParams
} from "react-router-dom";
function withRouter(Component) {
function ComponentWithRouterProp(props) {
let location = useLocation();
let navigate = useNavigate();
let params = useParams();
return (
<Component
{...props}
router={{ location, navigate, params }}
/>
);
}
return ComponentWithRouterProp;
}
You can now wrap and export your class-based components to withRouter
HOC in the very familiar way they were from v4/v5.
After that you can use useNavigate
from react-router-dom v6
.
const navigate = useNavigate()
navigate("/main")
Regarding your query that you've mentioned in the comment:
So should I create a separate component to add the above code or I should add the above code for each component that I want to use history? or should I add it into App.js?
To work around this issue first, create a new component withRouter
as indicated above, and then wrap CreateContent
component in a withRouter
function, when it is exported:
export default withRouter(CreateContent)
withRouter
will pass updated match, location, and history props to the wrapped component whenever it renders.
withRouter
reference in v5: https://v5.reactrouter.com/web/api/withRouter
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments