How to insert a Django template variable in a React script?

I am using Django Rest Framework with React.js. My page shows one user profile using api as follows:

http://localhost:8000/api/profile/[pk]

I want to dynamically set the url to respond to an ajax request in order to enable the correct pk so that it requests the correct user information from the server.

I could use a function like window.location.href and call a number from the end, but is there a way to do this by passing pk directly from the server, i.e. using a template variable?

+8
django reactjs
source share
1 answer

When rendering a component, you must pass pk as a support.

 <script> React.render(React.createElement(Profile, { userId: "{{ userId }}", urlPrefix: "/api/profile/" }), element); </script> 

A better alternative would be to simply select the user and then render the component. For example, with a superagent:

 superagent.get('/api/profile/{{ userId }}', function(res){ React.render(React.createElement(Profile, {user: res.body} ), element); }); 

Using a browser, you can include data in a script tag and use this in your code:

 <script>var _appData = {userId: "{{ userId }}"};</script> 

Or export the 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 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> 
+12
source share

All Articles