Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I insert a Django template variable into a React script?

Tags:

reactjs

django

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?

like image 727
YPCrumble Avatar asked Oct 21 '14 03:10

YPCrumble


1 Answers

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>
like image 145
Brigand Avatar answered Sep 28 '22 04:09

Brigand