I am using Django Rest Framework with React.js. My page shows one user's profile, using an api like this:
http://localhost:8000/api/profile/[pk]
I want to dynamically set the url for the react ajax request to include the proper pk, so that it requests the correct user's information from the server.
I could use a function like window.location.href and pop the number from the end, but is there a way to do this by passing the pk directly from the server, i.e., using a template variable?
When you render the component, you should pass the pk as a prop.
<script>
React.render(React.createElement(Profile, {
userId: "{{ userId }}",
urlPrefix: "/api/profile/"
}), element);
</script>
A better alternative might be to just fetch the user, and then render the component. For example, with superagent:
superagent.get('/api/profile/{{ userId }}', function(res){
React.render(React.createElement(Profile,
{user: res.body}
), element);
});
With browserify, you can either include data in a script tag, and use that in your code:
<script>var _appData = {userId: "{{ userId }}"};</script>
Or export modules using the -r
flag (.require()
in the api).
# sh
browserify -r react -r src/profile.js:profile.js
// js
b.require('react').require('src/profile.js', {expose: 'profile.js'});
And then use the modules in regular script tags
<script>
var React = require('react');
var Profile = require('profile.js');
React.render(React.createElement(Profile, {
userId: "{{ userId }}",
urlPrefix: "/api/profile/"
}), element);
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With