reactjs communicating between multiple file - reactjs

I am new to reactjs and trying to understand architecting a reactjs application. I have created two different js files with react code ( spc.js and index.js) The spc.js file contains all the reusable component definitions while the index.js consists of the calling component and the reactDom function. Both this files are called from an index.html file. please find the code below.
Index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Investor Relations</title>
<!-- Not present in the tutorial. Just for basic styling. -->
<link rel="stylesheet" href="spc.css" />
<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.6.15/browser.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div id="spticker_content">
</div>
<script type="text/babel" src="sharepriceticker.js"></script>
<script type="text/babel" src="../default/sharepriceticker/sharepriceticker.js"></script>
</body>
</html>
spc.js
var Companyname = React.createClass({
render: function() {
return ( < div className = "company_name" > {
this.props.compname
} < /div> );
}
});
var Exchange = React.createClass({
render: function() {
return ( < span className = "exch_text" > {
this.props.exchange
} < /span>);
}
});
index.js
var Sharepriceticker = React.createClass({
render:function(){
return(
<div className="spticker">
<div className="heading">
<Companyname compname="Indus Gas"/>
<Exchange exchange="(LON:INDI)"/>
</div>
</div>
);
}
});
ReactDOM.render(
<Sharepriceticker/>,
document.getElementById('spticker_content')
);
My code works fine if i combine the spc.js and index.js in single file, however it doesnt work if i seperate the two files
Thanks

One solution is to set your classes on the global scope. For example, your spc.js could be:
(function (app) {
app.reactClasses = app.reactClasses || { };
app.reactClasses.Companyname = React.createClass({
render: function() {
return ( < div className = "company_name" > {
this.props.compname
} < /div> );
}
});
app.reactClasses.Exchange = React.createClass({
render: function() {
return ( < span className = "exch_text" > {
this.props.exchange
} < /span>);
}
});
})(window.app || (window.app = { }))
Then your index.js could have:
<app.reactClasses.Companyname compname="Indus Gas"/>
<app.reactClasses.Exchange exchange="(LON:INDI)"/>
I hope this helps! (:

The combination should not be the part of react you have to use the common js pattern with require
let's say I have two component A and B
my A component should be like
var A=React.createClass({
render:function()
{
return(
// html content goes here
)
}
});
my Component B look like
var B=React.createClass({
render:function()
{
return(
// html content goes here
)
}
});
module.exports = B;
now if I want to use component A in Component B then I must have to use export.modules=A in component A and in Component B I have to import the component A like
in ES5
var A=require('B');
in ES6
import A from 'B'
now you can use the component A in your B Component like
var A=React.createClass({
render:function()
{
return(
<A />
)
}
});

Related

How to use WebView to show React jsx file

I can't see any support to React jsx local file. How can I use them in WebView ? Can someone help me .
I'm using in this case like this:
<WebView
source={{
uri: isAndroid
? 'file:///android_asset/android_asset/index.jsx'
: 'index.jsx'
}}
allowUniversalAccessFromFileURLs={true}
onShouldStartLoadWithRequest={request => {
return true
}}
useWebKit={false}
/>
UPDATE
I tried for hours but I can't find the way how to import React file to Javascript.
this is my react file like:
index.jsx
import * as React from 'react';`
export class TVChartContainer extends React.PureComponent {
componentDidMount(){ // Do something}
render(){
return (
<div
id={this.props.containerId}
className={'TVChartContainer'}
/>
);
}
}
You need to get HTML string. In WEB React you can render JSX by ReactDom but in ReactNative you can't do it.
The easiest way is generating html string according to your jsx and data. You can put everthing there. I show you several examples.
class MyInlineWeb extends Component {
componentDidMount(){ // Do something}
renderHtmlAndroid = (data) => {
return `<div>
<style>
.block {}
</style>
<div class="block">${data}<div>
<div>`
}
renderHtmliOs = (data) => {
return `<!DOCTYPE html>
<html>
<head>
<title>Title</title>
<meta charset="UTF-8" />
</head>
<body>
<div id="app">${data}</div>
</body>
</html>`
}
render() {
return (
<WebView
originWhitelist={['*']}
source={{html: isAndroid ? this.renderHtmlAndroid([]) : this.renderHtmliOs([])}}
/>
);
}
}

Script with jsx and script without jsx not working on the same page

I have a page where I want to test some react code. Both scripts are working independently, if they are alone in the page. If I add both, the script with jsx does not work. Is there an explanation for that behavior? Is it not allowed?
There is nothing about the code. I am guessing the imports cannot live together.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="index.css">
<title>My Website</title>
</head>
<body>
<div id="myroot"></div>
<div id="myBabel"></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="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
<!-- Load our React component. -->
<script src="js/index2.js"></script>
<script type="text/babel" src="js/index.jsx"></script>
</body>
</html>
Here the index2.js contents:
class App extends React.Component {
render() {
return React.createElement("div", null, React.createElement("h1", null, " the list "));
}
}
ReactDOM.render(React.createElement(App,null,null),
document.getElementById("myroot"));
And here a React with jsx:
class App extends React.Component {
state = {
/* Initial State */
input: "",
reversedText: ""
};
/* handleChange() function to set a new state for input */
handleChange = event => {
const value = event.target.value;
this.setState({
input: value
});
};
/* handleReverse() function to reverse the input and set that as new state for reversedText*/
handleReverse = event => {
event.preventDefault();
const text = this.state.input;
this.setState({
reversedText: text
.split("")
.reverse()
.join("")
});
};
render() {
return (
<React.Fragment>
{ /* handleReverse() is called when the form is submitted */}
<form onSubmit={this.handleReverse}>
<div>
{ /* Render input entered */}
<label>Text: {this.state.input}</label>
</div>
<div>
{ /* handleChange() is triggered when text is entered */ }
<input
type="text"
value={this.state.input}
onChange={this.handleChange}
placeholder="Enter a text"
/>
</div>
<div>
<button>Reverse Text</button>
</div>
</form>
{ /* Render reversed text */}
<p>Reversed Text: {this.state.reversedText}</p>
</React.Fragment>
);
}
}
ReactDOM.render(<App />, document.getElementById("myBabel"));
Like I said, the imports are working alone but both at the same time in the HTML page are not.
class List extends React.Component {
render() {
return React.createElement("div", null, React.createElement("h1", null, " the list "));
}
}
ReactDOM.render(React.createElement(List,null,null),
document.getElementById("myroot"));
If you check the console logs for your code you will find this error -
Uncaught SyntaxError: Identifier 'App' has already been declared.
You have both your components identified as App. So React needs different identifiers to keep track of each component. I changed one of the class name from App to List. This will work. Make sure to name your components.

How to use React.Component with renderToString method?

I tried to do the server side render using renderToString method.
function handleRender(req, res) {
const html = renderToString(
<Counter />
);
res.send(renderFullPage(html));
}
function renderFullPage(html) {
return `
<!doctype html>
<html>
<head>
<title>React Universal Example</title>
</head>
<body>
<div id="app">${html}</div>
<script src="/static/bundle.js"></script>
</body>
</html>
`
}
If the component like following it works:
Counter.js
const Counter = () => {
function testClick(){
console.log('test');
}
return (
<div>
<div onClick={testClick.bind(this)}>
test
</div>
</div>
);
};
export default Counter;
However, if I change Counter.js into following:
class Counter extends React.Component {
testClick(){
console.log('click');
}
render() {
return (
<div>
<div onClick={this.testClick.bind(this)}>
test btn
</div>
</div>
)
}
}
export default Counter;
It will show errors:
Uncaught Error: locals[0] does not appear to be a `module` object with Hot Module replacement API enabled. You should disable react-transform-hmr in production by using `env` section in Babel configuration.
So how to use React.Component with renderToString method?
I minimize the project and push to Github. Please have a look.
https://github.com/ovojhking/ssrTest/tree/master

React - Coding Error

I am following tutorial from: https://www.youtube.com/watch?v=OzqR10jG1pg
Using Code Editor: https://stackblitz.com
Coding error reads:
Error in index.js (36:10)
'}' expected.
Error line reads:
render: function () {
How do I get this code to work?
Here is my Code:
import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
class App extends Component {
constructor() {
super();
this.state = {
name: 'React'
};
}
render() {
return (
<div>
<Hello name={this.state.name} />
<p>
Start editing to see some magic happen :)
</p>
</div>
);
}
}
render(<App />, document.getElementById('root'));
<div id="example"></div>
<script type="text/babel">
var Bacon = React.createClass({
render: function () {
return (<h3>This is a simple component!</h3>);
}
});
ReactDOM.render(<Bacon />, document.getElementById('example'));
</script>
It looks like you are putting HTML code into your javascript (index.js) file. You should have a separate HTML file for that.
I can see you are trying to render two different apps.
First, when you use ReactDOM.render(<Bacon />, document.getElementById('example')); you're telling React to render the component Bacon in the HTML element that has an ID attribute 'example'.
Then, with render(<App />, document.getElementById('root'));, React will look for an element that has an ID attribute 'root'.
So you should have both elements in your HTML file, like the snippet below.
// index.js
class App extends React.Component {
constructor() {
super();
this.state = {
name: 'React'
};
}
render() {
return (
<div>
<div>{this.state.name}</div>
<p>
Start editing to see some magic happen :)
</p>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
<!-- index.html -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="example"></div>
<div id="root"></div>
<script type="text/babel">
var Bacon = React.createClass({
render: function () {
return (<h3>This is a simple component!</h3>);
}
});
ReactDOM.render(<Bacon />, document.getElementById('example'));
</script>

Add props to React render call with looping construct

Say I have an array ("props") that I want to render a React component with. Something like:
const props = [];
ReactDOM.render(<Comp prop0={props[0]} prop1={props[1]/>, document.getElementById('foo'));
Is there acceptable way to add props to a React component using some loop construct instead of "hardcoding" it?
Usually, you would use the spread operator there:
var props = {};
props.foo = 'something';
props.bar = 'something else';
ReactDOM.render(<Component {...props} />, someDomElement);
I suppose if you wanted to both render a variable number of children with a variable number of props, you could do it like so:
const React = require('react');
module.exports = function(children){
return React.createClass({
renderChildren: function(){
return children.map(function(Child){
return (
<div>
<Child {...Child.propz}/>
</div>
)
});
},
render: function(){
return (
<html lang="en">
<head>
<meta charset="UTF-8"></meta>
<title>Title</title>
</head>
<body>
<div>
{this.renderChildren()}
</div>
</body>
</html>
)
}
});
};

Resources