React component render in Django Template - reactjs

I have a Django view through which I want to render a React component. But unable to do so. This is my Django template.
{% extends "base.html" %}
{% block javascript %}
<script>
window.props = {{props}}; // make sure to escape your props to prevent XSS! See here for the source for the json filter: https://gist.github.com/pirate/c18bfe4fd96008ffa0aef25001a2e88f
window.react_mount = document.getElementById('react');
</script>
<!-- Load React. -->
<!-- Note: when deploying, replace "development.js" with "production.min.js". -->
<script src="https://unpkg.com/react#16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone#6/babel.min.js" crossorigin></script>
<script src="/static/components/{{component}}" type="text/babel"></script>
{% endblock javascript %}
{% block content %}
<div class="container">
<div class="card">
<div class="card-body">
<div id="react">
<!-- Contents get replaced by mounted React.Component -->
<i class="fa fa-lg fa-spinner fa-spin"></i><br><br>
<i class="pending">Loading components...</i><br><br>
</div>
</div>
</div>
</div>
{% endblock content%}
This is my React component.
import React from 'react'
import ReactDOM from 'react-dom'
class HelloWorld extends React.Component {
render() {
return <h1>Hello World!</h1>;
}
}
ReactDOM.render(
React.createElement(HelloWorld, window.props), // gets the props that are passed in the template
window.react_mount, // a reference to the #react div that we render to
)
I am getting following error:
Uncaught ReferenceError: require is not defined

I followed this solution and it works. The problem was that I need to configure webpack (see webpack.config.js file) which bundles the JS files.

Related

React component not rendered every time on website

I got a simple react component added to a web page and it is not rendering every time. It comes after I clear my browser history and then if I refresh my page it is not rendered. am I using old cdns or Babel?
This is my component and HTML.
React file find_new.js
'use strict';
class FindNew extends React.Component {
render() {
return (
<div>
<li className="list-inline-item">
<select className="selectpicker show-tick">
<option>Newly published</option>
<option>Recent</option>
<option>Old Review</option>
</select>
</li>
</div>
);
}
}
const domContainer = document.querySelector('#find_new');
ReactDOM.render(<FindNew/>, domContainer);
HTML
<div id="find_new"></div>
<script src="https://unpkg.com/react#16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js" crossorigin></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
<script type="text/babel" src="reactme/find_new.js"></script>

simple way to integrate React into Flask app?

Here is my flask project, which im trying to get a react file to work in.
In it, we have app.py, which contains the routes, and should be hitting index.html in the templates folder.
app = Flask(__name__)
#app.route("/stem")
# test channel
def qi():
return render_template('index.html')
in the html, im simple running the script for App.js,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="{{ url_for('static',filename='styles/App.css') }}">
<script src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone#6.26.0/babel.js"></script>
<title>nstem</title>
</head>
<body>
<script src="{{ url_for('static', filename='js/App.js') }}"> </script>
<div id="root">
</div>
</body>
</html>
which, in turn, should be running a function that creates a bunch of elements.
import React from 'react';
import './static/styles/App.css';
import ReactDOM from 'react';
import game from './vectors/game.svg';
import v1 from './vectors/v1.svg';
import v2 from './vectors/v2.svg';
import flower4 from './vectors/flower4.svg';
import unity from './vectors/unity.svg';
import box from './vectors/box.svg';
import map1 from './vectors/map1.svg';
// <img class="map1" src={map1}/>
function DataStructures() {
const section = 'lists';
return (
<div>
<section class = "section">Allah'u'abha</section>
<div>
<div >
<div></div>
<div class = "listBox1"></div>
<div class = "indexBox1"></div>
<div class = "boxIndex1"></div>
</div>
</div>
<div>
<div >
<div class = "listBoxes1"></div>
<div class = "listBoxes2"></div>
<div class = "listBoxes3"></div>
</div>
</div>
<div>
<div >
<div class = "listBoxes1b"></div>
<div class = "listBoxes2b"></div>
<div class = "listBoxes3b"></div>
<div class = "boxIndex1b"></div>
<div class = "indexValue"></div>
</div>
</div>
<div>
<div >
<img class="flower2" src={v1}/>
<img class="flower3" src={v2}/>
<img class="flower4" src={flower4}/>
</div>
<div class="metabox">
<img class="flower5" src={flower4}/>
</div>
<div >
<img class="box" src={v2}/>
</div>
</div>
</div>
);
}
ReactDOM.render(
<DataStructures />,
document.getElementById('root')
);
The issue is, nothing but the background color for the page is coming up. Im trying to understand what i'm missing here. Do i need to edit my project structure, or might it be something else?
Since your React component is in JSX form the problem is most likely because the JSX needs to be transpiled into JavaScript that is browser-readable. Toolchains you are probably used to like Create-React-App will transpile for you (using Babel) but in Flask as far as I know you have to handle it yourself.
With Flask there are a few tutorials for making a toolchain for integrating with React out there but if you already have a pretty extensive Flask app it can be tricky.
My workaround was to initialize NPM for the project, install the babel-cli package, pre-transpile JSX files into JS and then link the HTML page to the transpiled JS file.
You can install by running the following commands:
npm init -y
npm install babel-cli#6 babel-preset-react-app#3
From there, you run this command:
npx babel --watch (jsdirectory) --out-dir (outputdirectory) --presets react-app/prod
where (jsdirectory) is the path to the directory where your React component files written using JSX are, and (outputdirectory) is where you want your translated files to show up--use . for (outputdirectory) to have transpiled files appear in your root directory.
Once you have the outputted .js files try to associate them with the HTML page as you normally would using the script tag and it should render properly.

How to link react component to html?

I am trying to load react component from another js file, but i am not able to link that file...it says reference error..ads is not defined..I don't know how to solve this....i am doing this in django and react is also working fine.
//home.html
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="{% static 'css/home.css' %}" type="text/css"/>
<script src="{% static 'root/react.min.js' %}"></script>
<script src="{% static 'root/react-dom.min.js' %}"></script>
<script src="{% static 'root/browser.js' %}"></script>
<script src="{% static 'javascript/ads.js' %}"></script>
</head>
<body id="root">
<script type="text/babel">
class Home extends React.Component{
render(){
return(
<div id="home">
<Header/>
<div id="container">
<div id="left">
<User/>
<Foo/>
</div>
<Post/>
<div id="right">
<Tranding/>
<Ads/>
</div>
</div>
<div id="upload">
<img src="{% static 'images/large.jpg' %}"/>
<div id="caption">
<input type="text" placeholder="Write a caption"/>
</div>
</div>
</div>
)
}
}
// ads.js
export class Ads extends React.Component{
render(){
return(<div id="ads">
<div id="head">Ads</div>
</div>)
}
}
You are not using import in your script. You are trying to use the script tag to import... this does not work the same way. You should instead either import Ads from 'javascript/ads.js' or you leave the script inclusion and instead in your ads.js file attach window.Ads = Ads
Also, do not forget to use export syntax properly. It would be export default class Ads not export class Ads
Please make sure Ads class is exported from ads.js.

tried to load angular more than once, while creating custom directive

My index.html file and i tried to load the directive in this html file.
//
{% extends "base.html" %}
{% load staticfiles %}
{% block content %}
<div ng-app="myApp">
<div ng-controller="mainController">
{% verbatim %}
<div class="row">
<div class="column small-12">
<h1 class="up heading text_setting">{{title}}</h1>
</div>
</div>
<edit-cart></edit-cart>
<div class="row">
<div class="small-12 column"><h1 class="up heading">products total <span class="right">3000</span></h1> </div>
</div>
<div class="row">
<div class="small-10 block-center">
<button class="btn-block up heading text_setting ">checkout as guest</button>
<button class="btn-block up heading text_setting">log in/join</button>
</div>
</div>
</div>
{% endverbatim %}
</div>
{% endblock content %}
{% block customjs %}
<!-- common angular js -->
<script src="{% static 'angular_wrapper/shared/angular.min.js' %}"></script>
<script src="{% static 'angular_wrapper/shared/angular-route.js' %}"></script>
<script src="{% static 'angular_wrapper/shared/angular-mock.js' %}"></script>
<!-- app -->
<script src="{% static 'angular_wrapper/shared/app.js' %}"></script>
<!-- controller -->
<script src="{% static 'angular_wrapper/controller/maincontroller.js' %}"></script>
<!-- directives -->
<script src="{% static 'angular_wrapper/directives/directive-editcart.js' %}"></script>
<!-- angular services -->
<script src="{% static 'angular_wrapper/services/service-editcart.js' %}"></script>
{% endblock customjs %}
editcart.html is this
//
<div class="row">
<P>{{move.name}}</P>
<P>{{move.email}}</P>
</div>
and angular code
//
var app = angular.module('myApp', ['ngRoute']);
app.controller('mainController', ['$scope', function($scope) {
$scope.move={
name:'sonu',
email:'sonu.jun3#gmail.com'
};
}]);
//directive
app.directive('editCart', function() {
return {
restrict: 'E',
templateUrl: 'directives/editcart.html'
};
});
console-image attached here
I am creating custom directive for my Web app but couldn't fix this bug.
don't know what is wrong.
I have included all js please help?
As stated in this GitHub issue by Michael Bromley (the second answer from the top), the problem is that Angular is trying to instantiate a template it's not able to find, so it just reload the index.html file which contains the angular script, so the error.
I resolved this issue by indicating in the templateUrl the full path of the file from the root of the public directory (or the one from which you are attempting to take the file from).
So in my case was modules/teams/client/directives/notification.html insted of directives/notification.html.
I don't knwo if it's the right solution, but worked for me.
And what I was really disappointed by was the fact that angular didn't tell me nothing about this missing template, but when I put modules/directive(which is a folder) it gives me back an error.
Really strange behaviour, I expected at least to be informed that the template was not loaded correctly.

React renderComponent replace DOM

JSX code:
var App = React.createClass({
render: function() {
return <div className="darken">hello world</div>
}
});
React.renderComponent(<App/>, document.querySelector('.main'))
HTML:
<body>
<header>welcome</header>
<div class="main"></div>
</body>
React.renderComponent will append rendered JSX to <div class="main">. Output of HTML will be:
<body>
<header>welcome</header>
<div class="main">
<div class="darken">hello world</div>
</div>
</body>
Is it possible React.renderComponent replace <div class="main">, so what I expect like this:
<body>
<header>welcome</header>
<div class="darken">hello world</div>
</body>
Was having a problem getting my component to render in React 0.14.0. My solution was make sure your scripts have a special type:
<script type="text/babel" src='js/app.js'></script>
Include these three libraries:
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
Then use ReactDOM.render():
ReactDOM.render(<Timer start={Date.now()} />, document.getElementById('app'));
I'm not even using ES6 or a build system. Simple solution to get text on the screen with react.js
Sure, just use:
React.render(<App/>, document.body);
Had a similar problem and this is what I came up with.
Replace it with a simple span tag so it doesn't affect your styling.
const appContainer = document.createElement('span')
const mainEl = document.querySelector('.main')
mainEl.parentNode.replaceChild(appContainer, mainEl)
React.renderComponent(<App/>, mainEl)
Which will produce
<body>
<header>welcome</header>
<span> <!-- this acts as the container for react -->
<div class="darken">hello world</div>
</span>
</body>

Resources