Reputation: 550
this is my code example but I do not know how to take the value and after use it
class View extends Component {
componentDidMount() {
var id = {match.params.id}
}
render() {
return(
<Router>
<div>
<Route path="/View/:id" component={Child}/>
</div>
</Router>
)
}
}
Upvotes: 4
Views: 50963
Reputation: 47
I had the same issue, finally, this code worked. It may be happening because you are following an older resource that is using an older version of react-router-dom version 5 whereas you are using version 6. In version 6 there were many breaking API changes. The Route components no longer use component or render props, the element prop that is passed a valid JSX literally replaced them. route props (history, location, and match) also no longer exist, the routed components must use the React hooks to access them now.
import { useParams } from 'react-router-dom';
const ProductDetails = () => {
const dispatch = useDispatch();
const { id } = useParams();
const {product,loading,error} = useSelector((state) => state.productDetails);
useEffect (()=>{
dispatch(getProductDetails(id))
},[dispatch,id])
return (
<Fragment>
<div className="ProductDetails">
<div>
<Crousel>
{product.images && product.images.map((item, i) => (
<img className='CrouselImage'
key={item.url}
src={item.url}
alt={`${i} side`} />
))}
</Crousel>
</div>
</div>
</Fragment>
)
}
Replace all your {match.params.id} with just id It should work fine.
Upvotes: 0
Reputation: 21
{match.params.id} like variable.
this.id = this.props.match.params.id;
this.apartament = json.find((entry) => entry.id === this.id);
Upvotes: 2
Reputation: 1016
You can do it this way :
import { useParams } from 'react-router-dom';
function GetId() {
const { id } = useParams();
console.log(id);
return (
<div>
your expected id : {id}
</div>
);
}
Upvotes: 7
Reputation: 150
This might help you. Just create constructor i.e constructor(props) {}
and inside it declare the id
as a state
variable to the class.
Pass the value of match.params.id
to the id
by using id: this.props.match.params.id
.
Now u can access the state variable anywhere in your code and hope it solves your problem.
class View extends Component {
constructor(props){
super(props);
this.state = {
id : this.props.match.params.id
}
}
componentDidMount() {
var id = {this.state.id}
}
render() {
return(
<Router>
<div>
<Route path="/View/:id" component={Child}/>
</div>
</Router>
)
}
}
Upvotes: 9
Reputation: 2851
Look here:
https://github.com/reactjs/react-router-tutorial/tree/master/lessons/06-params
You component will be injected a prop params
which you'll be able to get to like this:
<div>
<h2>{this.props.params.id}</h2>
</div>
Upvotes: 0