I have been trying to call the profile link using a state variable id, to navigate to a specific user's profile, the method below doesn't work but if I am able to put the 'id' value into the url as I am trying to do below it will work because in App.js:
<Route path="/user/:id" component={Profile} />
And I need the link below to be clickable on the home page to take a logged in user to their profile by fetching their id from the server and saving it in a state variable and then parsing the value into the url dynamically. Home.js:
constructor(props) {
super(props);
id: localStorage.getItem("id");
}
componentDidMount() {
const payload = {
"username": localStorage.getItem("username")
};
fetch(ID_FROM_USERNAME_URL, {
method: 'POST',
headers: {
"Authorization": localStorage.getItem("token"),
"Accept": "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(payload)
})
.then(response => response.json())
.then((data) => {
console.log("id from server:")
console.log(data);
localStorage.setItem("id", data);
});
}
In render() return ()
<Button color=
"link"><Link to="/user/${this.state.id}">Profile</Link></Button>`
How can I parse the state variable's value into this Link element?
Thanks
CodePudding user response:
you are using template literal wrong.. it need to be passed as variable and in backticks
<Link to={`/user/${this.state.id}`}>Profile</Link></Button>
CodePudding user response:
You need to use template literal, it's a nice feature added in ES6.
<Link to={`/user/${this.state.id}`}>Profile</Link></Button>
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
Also, it looks like your code is broken, you don't have state and setState and it's not wise to use storage for this task.
