I have managed to render my component on a div on my template like so:
Index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Example</title>
</head>
<body>
{% load render_bundle from webpack_loader %}<h1>Example</h1>
<div id="react-app"></div>
{% render_bundle 'main' %}
</body>
</html>
My react app:
Index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
const rootElement = document.getElementById('react-app');
ReactDOM.render(<App />, rootElement);
Whats a good approach to pass in data to react? i'm using Django templates
It is possible to pass props to the root element through data attributes and pass them to root element in index.js
<div
id="root"
data-custom-props='{aKey: "a value"}'
></div>
index.js file:
ReactDOM.render(<App {...(root.dataset)}/>, root);
A common pattern is to output a json string into a script tag, which you can then refer to in your init function.
For example:
// Above where you include your main bundle
<script>
window.__INITIAL_STATE.__ = { your: 'DATA', encodedIn: 'json', here: true }
</script>
You can then reference window.__INITIAL_STATE__ in your index.js and pass data as props into your root component.
What data do you want to pass to react?
Props is the concept that allow user to pass data from one component to another within react. It is not made to pass data from outside world to react app.
I believe this answer can guide you in right direction.
How to get Django and ReactJS to work together?
also read following to get some idea of back-end and front-end working together.
http://geezhawk.github.io/using-react-with-django-rest-framework
http://www.openmindedinnovations.com/blogs/3-ways-to-integrate-ruby-on-rails-react-flux
Related
I'm trying to override the primary color in Bootstrap but it just doesn't work. Btw I'm using NextJS.
This is my "globals.scss" which I have imported in "_app.js".
$primary: black;
#import 'bootstrap/scss/bootstrap';
And I have imported Bootstrap in index.js like this
import 'bootstrap/dist/css/bootstrap.css'
I tried looking it up but everything I tried didn't work.
What I've tried:
Importing functions, variables, and mixins from Bootstrap SCSS.
Rearranging the imports.
Importing bootstrap/scss/bootstrap.scss to "_app.js"
But I've noticed that in the inspector it says my primary color is black but then right above it changes back to the original:
Below:
Above:
How to override Bootstrap variables in a Next.js project
Let's create an app and try to change the $primary color from default to black.
App structure:
Code:
index.js
import Head from 'next/head'
import styles from '../styles/Home.module.css'
export default function Home() {
return (
<div className={styles.container}>
<Head>
<title>Create Next App</title>
<meta name='description' content='Generated by create next app' />
<link rel='icon' href='/favicon.ico' />
</Head>
<main className={styles.main}>
<h1 className={styles.title}>
Welcome to <a href='https://nextjs.org'>Next.js!</a>
</h1>
<button type='button' className='btn btn-primary mt-4'>Primary</button>
</main>
</div>
)
}
_app.js
import '../styles/globals.css'
import { useEffect } from 'react'
function MyApp({ Component, pageProps }) {
useEffect(() => {
require('bootstrap/dist/js/bootstrap.bundle.min.js');
}, []);
return <Component {...pageProps} />
}
export default MyApp
globals.scss
$primary: black;
#import '../node_modules/bootstrap/scss/bootstrap';
Screenshot:
I think the problem of your codes is about the order of importing files. If you use globals.scss file to change bootstrap default values, Then you must import that file after your main bootstrap file. I'm not sure about the project structure you have, but for example if you imported Bootstrap in index.js file, change that file from just this:
import 'bootstrap/dist/css/bootstrap.css'
To something like this:
import 'bootstrap/dist/css/bootstrap.css'
import 'your/path/to/globals.scss'
Maybe that overrides the bootstrap file with your custom file.
I built a reactjs app which i want to use as simple webpart of my site.
Means my site can have multiple webparts (also of the same reactjs app) like a weather app.
By default i defined the element id where the reactjs app should hook in.
But now i want to pass this id as parameter to the reactjs app so that i can have the app multiple times on my site.
Here is an example of what my code should lokks like:
<html>
<head>
</head>
<body>
<div class="some-div">
<div id="FirstWebPart">
<!-- Place where the app should hook in -->
<script src="path/to/reactjs/app.js"></script>
</div>
</div>
<div class="some-other-div">
<div id="SecondWebPart">
<!-- Place where the app should hook in again -->
<script src="path/to/reactjs/app.js"></script>
</div>
</div>
</body>
</html>
Important is that both apps are referencing the same source .js file but have different configs.
E.G.
The first webpart should show the weather of country 1, the second webpart should show the weather of country 2.
The logic is the same but the parameter changes the content.
Any ideas how i could do this?
I'd do it via a function that would then instantiate the React part and connect it with the provided root element. The same function could also receive the country code.
<html>
<head>
</head>
<body>
<div class="some-div">
<div id="FirstWebPart">
</div>
</div>
<div class="some-other-div">
<div id="SecondWebPart">
</div>
</div>
<script src="path/to/reactjs/app.js"></script>
<script>
myapp(document.getElementById("FirstWebPart"), "ZA");
myapp(document.getElementById("SecondWebPart"), "BR");
</script>
</body>
</html>
Not sure if "webpart" refers to ASP.NET, but I didn't see any "ASP.NET" tag on your question.
if I understand the question correctly, you need to create 2 react components: root, child. pass the country and weather from root to child
root:
import React from 'react';
import Child from './Child';
const root = () => {
const arr = [{country: 'US', weather: 'sunny'}, {country: 'UK', weather: 'rainy'}];
return <body>
{arr.map( a=><Child country={a.country} weather={a.weather} /> )}
</body>
}
export default root;
Child:
import React from 'react';
const Child = (props)=> {
return <div class="some-div">
<div id={props.country}>
<span>{props.weather}</span>
</div>
</div>
}
export default Child;
Im starting coding reactjs and im confusing how html5 work on reactjs. Do we need to build a separate html5 sheet or code html5 direct into jsx sheet?
React is component based java-script lib. so on your html code just link jsx by main.js code structure. your xml code build and make application in the extension of JSX like App.jsx . Refer here to build react app
index.html
This is just regular HTML. We are setting div id = "app" as a root element for our app and adding index.js script which is our bundled app file.
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<title>React App</title>
</head>
<body>
<div id = "app"></div>
<script src = "index.js"></script>
</body>
</html>
App.jsx
import React from 'react';
class App extends React.Component {
render() {
return (
<div>
Hello World!!!
</div>
);
}
}
export default App;
main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App />, document.getElementById('app'));
In my webpack, the entry point of the application is set to index.js:
entry: {
app: [
'react-hot-loader/patch',
'./client/index.js'
]
In node Js, For path / in my application, I am routing it to index.html
from routes.js on server side using:
app.route('/*')
.get((req, res) => {
res.sendFile(path.resolve(`${app.get('appPath')}/index.html`));
});
Above code understandably serves index.html.
But what if I wanted my application routing to be initialized using React-router?
index.html gets rendered but I don't see index.js getting initialized at all.It is defined as entry point in webpack so that should happen ,right?
Problem: To have React-routing initialized which should work once the flow gets to index.js
My routes.js in client folder looks like this :
import React from 'react';
import {Route, IndexRoute} from 'react-router';
import About from './components/About/About';
import Header from './components/Header/Header';
import Outlet from './components/Home/SelectOutlet';
console.log("routes file client")
export default (
<Route path="/" component={Header}>
<IndexRoute component={Outlet}/>
<Route path="about" component={Footer}/>
</Route>
);
and index.js
import 'babel-polyfill'; //certain functions like array.from , set, map can't be transpiled by babel so ue poyfill for that
import React from 'react';
import { render } from 'react-dom';
import { Router, browserHistory } from 'react-router';
import routes from './routes';
//import '../node_modules/bootstrap/dist/css/bootstrap.min.css'; //webpack can import CSS files too
import './styles/styles.css';
render((
<Router history={browserHistory} routes={routes}/>),
document.getElementById('app')
);
console.log("In index js render ")
Consoles in index.js and routes.js never get consoled and the application just serves index.html because of express routing
my webpack file is taken from here: https://github.com/Hashnode/mern-starter
but I don't see bundle.js getting created anywhere with npm start command.
Edit:
error screenshot:
screen 1:
error message
When I click on this error message:
I get all the content from html in js:
<!DOCTYPE html>
<html>
<head>
<title>
ABC
</title>
</head>
<body>
<h1> XYZ</h1>
<div id="app"></div>
<script src="index.js"></script>
</body>
</html>
Well... Are you including
<script src="index.js"></script>
in your index.html?...
Is possible retrieve multiples html partials in one single html? I've the next situation:
Template: {header} {main} {footer}
/index: header:"Welcome" main:"welcome text" footer:""
/help: header:"Help title" main:"faq tips" footer"Back to home"
using ng-include I've to retreive 6 html from server. If I will retrive multiples partials in one html then I will retrieve 2 html from server only, one for /index and one for /help.
This situation is a small example the real situation.
The tag script with type ng-template don't work for me, because the script must be include before of ng-include.
Thanks!
Update 04/07/12:
I seek to update more than one div at a time, with an unique html retreive. I don't like this:
function IndexCtrl($scope) {
$scope.mainPage = 'partials/index/index.html';
$scope.headerTemplate = 'partials/index/header.html';
$scope.footerTemplate = 'partials/index/footer.html';
}
After in the template use ng-includes for include these partials. I think that this is not the correct way. There is other way?
Thanks!
Templates can be embedded in the main html. For example, with the following index.html:
<!DOCTYPE html>
<html ng-app=app>
<meta charset=utf-8>
<title>App</title>
<ng-view>Loading...</ng-view>
<script type=text/ng-template id=partial1.html>
<p>foo = {{foo}}</p>
</script>
<script type=text/ng-template id=partial2.html>
<p>Contents of partial2.html</p>
</script>
<script src=app.js></script>
you can use the following app.js:
angular.module('app', [], ['$routeProvider', '$controllerProvider', function($routeProvider, $controllerProvider) {
$routeProvider.when('/p1', { templateUrl: 'partial1.html', controller: 'Partial1' });
$controllerProvider.register('Partial1', ['$scope', function($scope) {
$scope.foo = 'bar';
}]);
}]);
The documentation for the $templateCache service has more details.
What I do is use template instead of templateUrl, and use the requirejs text plugin to load the templates. that way for development you can have thousands of files for your templates, but once you minify you only have one javascript file with all the templates inlined.
I created an open source project which is setup for backbone but can easily be modified for angular which does the minification and requirejs text plugin wiring for you: http://github.com/davidjnelson/agilejs