How do I join two elements and then render them in React? - javascript

It's simple. I have a render function with two elements
render() {
let elem1 = <div>Foo</div>;
let elem2 = <div>Bar</div>;
return(elem1 + elem2); // How do I render elem1 below elem2?
}
I want the output to be equivalent to this
<div>
Foo
</div>
<div>
Bar
</div>

Simple like this:
render() {
let elem1 = <div>Foo</div>;
let elem2 = <div>Bar</div>;
return (
<div>
{elem1}
{elem2}
</div>
);
}
You should read and practice more JSX in here

If you are using React > 16.2 you can use the new Fragment component
render() {
let elem1 = <div>Foo</div>;
let elem2 = <div>Bar</div>;
return (
<React.Fragment>
{elem1}
{elem2}
<React.Fragment/>
);
}
The main advantage over using a div is that it doesn't add any elements to the page and is more readable than returning an array.

render() {
let elements=new Array();
elements.push(<div>Foo</div>);
elements.push(<div>Bar</div>);
return elements;
}
So basically you can return array of children.

You can just return the two elements in the render method instead of declaring them and return them directly. Like this
render() {
return (
<div>
<div>Foo</div>
<div>Bar</div>
</div>
)
}

Extending on #Martin's answer above: If you are starting with latest version of React you should try and use React.Fragment as grouping element. Here is the reactjs documentation for it: https://reactjs.org/docs/fragments.html
There is also a shorter syntax for React.Fragment which is <>{elements}</>. However support for short syntax is not fully available yet.
Here is a codepen link for problem you are trying to solve: https://codepen.io/bdevapatla/pen/QxaKEq

Related

JS Variable AS html attribute [duplicate]

Setting an attribute in React is straightforward if you know the key, e.g.
data-500={this.props.YDistance}
but how can one dynamically set part of the key. e.g.
data-{this.props.YDistance}="valueHere"
var Test = React.createClass({
render: function() {
return (
<div data-{this.props.YDistance}="valueHere">
{this.props.children}
</div>
);
}
});
ReactDOM.render(
<Test YDistance="500">Hello World!</Test>,
document.getElementById('container')
);
There are libraries that require this kind of attribute setting (e.g. skrollr et al)
You could use an object to store the dynamic properties and then use JSX spread attributes.
https://facebook.github.io/react/docs/jsx-spread.html
const propBag = { [`data-${foo}`] = 'bar' };
return (
<div {...propBag}>
{this.props.children}
</div>
);
That is using the computed properties feature of ES6 as well as template literal strings. If you are not using ES6 features you could do an ES5 implementation like so:
var propBag = {};
propBag['data-' + foo] = 'bar';
return (
<div {...propBag}>
{this.props.children}
</div>
);

Changing a html variable in react

I have the following variable in React
let Example = (
<div>
Hello World
</div>
);
I would like to change its content (text, tags, etc.)
Is that possiable to do?
What is the type of this variable?
Thanks
You can just overwrite your variable in another statement and this is a jsx Element.
https://reactjs.org/docs/introducing-jsx.html
Maybe you are looking for react components and props?
https://reactjs.org/docs/components-and-props
The type of your variable would be a JavaScript function and you can use react props to modify your content.
Use functions!
const myContent = () => {
// Some js
return 'Hello!';
}
const Example = () => (
<div>
{myContent()}
</div>
);
If you want to change the content of a JSX snippet that's a crystal clear hint that what you need is a component.
In your example, you can try something like this.
const SayHello = ({ name }) => <div>Hello {name}</div>
Then you can use it as a regular component.
<SayHello name="world" />
You can bound the value to a variable, and then the component will be updated with any update of that variable.
let name = this.aMethodToGetAValue();
return <SayHello name={name} />

How to map a nested array in React.js?

Issue: I can only render one iteration of my array.
My desired result of course is to get the entire length of array objects.
Adding [key] to my rendered object fields is the only method that gives me any output. Without declaring the key in this way, I get nothing
Child Component
...
const Potatoes = ({potatoes}) => {
const PotatoItems = potatoes.map((potato, key) => {
if ([potato] == ''){
return false
} else {
return (
<li key={key}>
<span>{potato[key].name}</span>
<span>{potato[key].flavor}</span>
</li>);
}
});
return (
<div>
<ul>
{PotatoItems}
</ul>
</div>
);
};
Parent Component
...
render () {
const potatoes = new Array(this.props.potatoes);
return (
<section style={divStyle}>
<Potatoes potatoes={potatoes} />
</section>
)
}
Simply removing new Array() from around the potatoes constant fixes your issue.
It seems like you may have created an unnecessary additional array.
Then you can remove those [key] references on your object in the child component and you should be good to go!
Does this fix your issue?

Dynamically set attribute key (e.g. data-{foo}="bar") in React

Setting an attribute in React is straightforward if you know the key, e.g.
data-500={this.props.YDistance}
but how can one dynamically set part of the key. e.g.
data-{this.props.YDistance}="valueHere"
var Test = React.createClass({
render: function() {
return (
<div data-{this.props.YDistance}="valueHere">
{this.props.children}
</div>
);
}
});
ReactDOM.render(
<Test YDistance="500">Hello World!</Test>,
document.getElementById('container')
);
There are libraries that require this kind of attribute setting (e.g. skrollr et al)
You could use an object to store the dynamic properties and then use JSX spread attributes.
https://facebook.github.io/react/docs/jsx-spread.html
const propBag = { [`data-${foo}`] = 'bar' };
return (
<div {...propBag}>
{this.props.children}
</div>
);
That is using the computed properties feature of ES6 as well as template literal strings. If you are not using ES6 features you could do an ES5 implementation like so:
var propBag = {};
propBag['data-' + foo] = 'bar';
return (
<div {...propBag}>
{this.props.children}
</div>
);

How to loop and render elements in React.js without an array of objects to map?

I'm trying to convert a jQuery component to React.js and one of the things I'm having difficulty with is rendering n number of elements based on a for loop.
I understand this is not possible, or recommended and that where an array exists in the model it makes complete sense to use map. That's fine, but what about when you do not have an array? Instead you have numeric value which equates to a given number of elements to render, then what should you do?
Here's my example, I want to prefix a element with an arbitrary number of span tags based on it's hierarchical level. So at level 3, I want 3 span tags before the text element.
In javascript:
for (var i = 0; i < level; i++) {
$el.append('<span class="indent"></span>');
}
$el.append('Some text value');
I can't seem to get this, or anything similar to work in a JSX React.js component. Instead I had to do the following, first building a temp array to the correct length and then looping the array.
React.js
render: function() {
var tmp = [];
for (var i = 0; i < this.props.level; i++) {
tmp.push(i);
}
var indents = tmp.map(function (i) {
return (
<span className='indent'></span>
);
});
return (
...
{indents}
"Some text value"
...
);
}
Surely this can't be the best, or only way to achieve this? What am I missing?
Updated: As of React > 0.16
Render method does not necessarily have to return a single element. An array can also be returned.
var indents = [];
for (var i = 0; i < this.props.level; i++) {
indents.push(<span className='indent' key={i}></span>);
}
return indents;
OR
return this.props.level.map((item, index) => (
<span className="indent" key={index}>
{index}
</span>
));
Docs here explaining about JSX children
OLD:
You can use one loop instead
var indents = [];
for (var i = 0; i < this.props.level; i++) {
indents.push(<span className='indent' key={i}></span>);
}
return (
<div>
{indents}
"Some text value"
</div>
);
You can also use .map and fancy es6
return (
<div>
{this.props.level.map((item, index) => (
<span className='indent' key={index} />
))}
"Some text value"
</div>
);
Also, you have to wrap the return value in a container. I used div in the above example
As the docs say here
Currently, in a component's render, you can only return one node; if you have, say, a list of divs to return, you must wrap your components within a div, span or any other component.
Here is more functional example with some ES6 features:
'use strict';
const React = require('react');
function renderArticles(articles) {
if (articles.length > 0) {
return articles.map((article, index) => (
<Article key={index} article={article} />
));
}
else return [];
}
const Article = ({article}) => {
return (
<article key={article.id}>
<a href={article.link}>{article.title}</a>
<p>{article.description}</p>
</article>
);
};
const Articles = React.createClass({
render() {
const articles = renderArticles(this.props.articles);
return (
<section>
{ articles }
</section>
);
}
});
module.exports = Articles;
Array.from() takes an iterable object to convert to an array and an optional map function. You could create an object with a .length property as follows:
return Array.from({length: this.props.level}, (item, index) =>
<span className="indent" key={index}></span>
);
I'm using Object.keys(chars).map(...) to loop in render
// chars = {a:true, b:false, ..., z:false}
render() {
return (
<div>
{chars && Object.keys(chars).map(function(char, idx) {
return <span key={idx}>{char}</span>;
}.bind(this))}
"Some text value"
</div>
);
}
You can still use map if you can afford to create a makeshift array:
{
new Array(this.props.level).fill(0).map((_, index) => (
<span className='indent' key={index}></span>
))
}
This works because new Array(n).fill(x) creates an array of size n filled with x, which can then aid map.
I think this is the easiest way to loop in react js
<ul>
{yourarray.map((item)=><li>{item}</li>)}
</ul>

Categories