Add props to React render call with looping construct - reactjs

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>
)
}
});
};

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.

React: How to mount all components on page?

I want to be able to mount React components based on the HTML markup of a document rendered by a PHP framework and I can't find a way to achieve this.
Here is the HTML markup of my document:
<html>
<head>
<link rel="stylesheet" href="css/index.css">
</head>
<body>
<div id="app">
<Foo bar="lorem"></Foo>
<Foo bar="ipsum"></Foo>
<Foo bar="dolor"></Foo>
</div>
<script src="js/index.js"></script>
</body>
</html>
Here is the Foo component implementation (foo.js):
const React = require('react');
class Foo extends React.Component {
render() {
return React.createElement('div', {
className: 'foo'
}, `Hello ${this.props.bar}`);
}
}
module.exports = Foo;
And here is my App implementation (app.js):
const React = require('react');
const ReactDOM = require('react-dom');
require('./foo');
ReactDOM.render(
React.createElement('div'),
document.getElementById('app')
);
module.exports = {};
I'm expecting React to recursively mount every components found inside the #app div but for some reason only the #app div is mounted resulting in the following markup:
<div id="app">
<div data-reactroot=""></div>
</div>
I can't put my fingers on what I am doing wrong here.
So, in you app.js when you are rendering react DOM
ReactDOM.render(
React.createElement('div'),
document.getElementById('app')
);
In this case you are creating a div element and rendering it inside root div with id=app
In order to create multiple foo elements all you have to do is this
const Foo = require('./foo');
ReactDOM.render(
<div>
<Foo bar="lorem"></Foo>
<Foo bar="ipsum"></Foo>
<Foo bar="dolor"></Foo>
</div>
document.getElementById('app')
);
Hope this helps

Can we call child component outside parent render function?

Hi I'm new in React is there a way to call child component from parent component outside the render function ?? below is my sudo code,
any idea !!!!!!
var Parent React.createClass({
someFunction: function(){
//can I call Child component from here on every click
// as this will rerender the child component only on each click
// leaving parent component unrendered
},
render: function(){
}
})
The answer is NO. You've your answer in your question.
Let me explain. A component can be called as a child component only if it is used in the parent component, meaning, the child component should be used inside the render() of parent component. So, you cannot call a child component out of parent's render.
To achieve you requirement, you can use state to re-render the child component.
<script src="https://unpkg.com/babel-core#5.8.38/browser.min.js"></script>
<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>
<script type="text/babel">
const Child = React.createClass({
render() {
return <h1>Hello, world!</h1>
}
})
const Parent = React.createClass({
getInitialState() {
return {
renderChild: false
}
},
onClick(){
this.setState({
renderChild: !this.state.renderChild
})
},
render(){
return <div>
<button onClick={this.onClick}>{this.state.renderChild ? 'Hide' : 'Show'} Child</button>
{
this.state.renderChild &&
<Child />
}
</div>
}
})
ReactDOM.render(<Parent />, document.getElementById('example') );
</script>

reactjs communicating between multiple file

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 />
)
}
});

Resources