Reputation: 85
I have app.js as the parent and uploadlist.js as the child. I am passing "userid" which is defined in app.js to uploadlist.js. This is my try:
app.js :
export default class App extends Component {
state = {
userrole : '',
custid : ''
};
componentDidMount() {
if(localStorage.login)
{
const currentuser = JSON.parse(atob(localStorage.login.split(".")[1]));
this.setState( {userrole: currentuser.role });
this.setState( {custid: currentuser.id });
}
}
render() {
if(this.state.userrole === "Customer"){
const userid=this.state.custid;
console.log(userid); //This properly returns the userid in console.
return (
//some code
<Route path="/Uploadlist" render={props => <UploadList userid={props.match.params.userid} />}/>
uploadlist.js:
export default function Uploadlist() {
const userid = this.props.userid;
console.log(userid);
This returns "TypeError: Cannot read property 'props' of undefined" error. How can I solve this?
Upvotes: 0
Views: 66
Reputation: 1195
UploadList is a functional component. Your route passes values top the component but when you defined UploadList, you did not accept any props as parameter.
It should be
function UploadList(props) {
.....
}
export default UploadList;
Or like @certainperformance answered, you could even use ES5 de-structuring to destructure the props parameter.
If you want to use 'this' use a class based component but that's a bit archaic and functional components are the best way to go for it these days
Upvotes: 0
Reputation: 5497
when you want to pass props to the component rendered via Route
use render
prop instead of component
.
Change your component as below
<Route path="/Uploadlist" render={props => <UploadList userid={props.match.params.userid} />}/>
Also you are trying to access props.match.params.userid
you won't have the userId here because you are rendering this component for the path /Uploadlist
. But if the props.match
is from a parent component which renders this Route
then to avoid name collision change the name of your props as
render={routeProps => <UploadList userid={props.match.params.userid} {...routeProps} />}
Now you can access the props in your component as
export default function Uploadlist({ userid }) {
console.log(userid);
Refer
Upvotes: 0
Reputation: 370629
Uploadlist
is a functional component. It doesn't have this
- rather, its props will be in the first parameter passed to the function, in the shape of an object.
export default function Uploadlist({ userid }) {
console.log(userid);
or use a class component to reference this.props
export default class Uploadlist() {
render() {
console.log(this.props.userid);
Upvotes: 2