I'm trying to pass object props to Payments component using render method in route.
I have tried pass props to the functional components, but still no luck.
App.js
class App extends Component {
state = {
user: {},
};
componentDidMount() {
const url = "/api/current-user";
fetch(url, {
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
credentials: "same-origin",
method: "GET",
})
.then((response) => {
if (!response.ok) {
return response.json().then((err) => {
throw err;
});
}
return response.json();
})
.then((results) => {
const user = results.user;
this.setState({
user,
});
})
.catch((error) => {
console.log("Error", error);
});
}
render() {
console.log(this.state.user);
return (
<div className="container">
<h1 className="is-size-3">Test</h1>
{this.state.user && (
<Route
exact
path="/payments"
render={(props) => <Payments {...props} user={this.state.user} /> }
/>
)}
</div>
);
}
}
Payments.js
function Payments() {
return (
<>
<CheckoutForm user={this.props.user} />
<CurrentSubscription subscription={subscription} />
</>
);
}
I have tried a few approaches,but still I'm getting 'props' of undefined.
Thanks in advance
This should work
function Payments(props) {
return (
<>
<CheckoutForm user={props.user} />
<CurrentSubscription subscription={subscription} />
</>
);
}
Always put props in the function or class component f you have props, like so:
function Payments({user}) {
return (
<>
<CheckoutForm user={user} />
<CurrentSubscription subscription={subscription} />
</>
);
}
or
function Payments(props) {
return (
<>
<CheckoutForm user={props.user} />
<CurrentSubscription subscription={subscription} />
</>
);
}
By the way, in functional component, there's no this
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.