score:5
first, you can't return multiple sibling elements as jsx without a parent container, unless you put them into an array (though you can't return arrays from render
methods until react adds support for returning fragments).
this is invalid:
return (
<div>first sibling</div>
<div>second sibling</div>
);
these are both valid:
return (
<div>
<div>first sibling</div>
<div>second sibling</div>
<div>
);
// vs.
// (notice this requires adding keys)
return ([
<div key={1}>first sibling</div>,
<div key={2}>second sibling</div>
]);
second, if you want to use a conditional statement to render components, you have to do it like this:
{(index % 2 === 0) &&
<div>this will render when index % 2 === 0</div>
}
the reason this works is that the &&
operator in javascript evaluates to the second operand (your jsx in this case) if the first operand is truthy. you can also use ternary statements, like this:
{(index % 2 === 0) ?
<div>this will render when index % 2 === 0</div>
:
<div>this will render when index % 2 !== 0</div>
}
putting this all together
var items = ['abc', '123', 'doe', 'rae', 'me'];
return (
<div>
{items.map((item, index) => (
<div>
<span dangerouslysetinnerhtml={{ __html: item }}></span>
{(index % 2 === 0) &&
<h1>test output/h1>
}
</div>
))}
</div>
}
[edit] important note
i should mention that whenever you're rendering an array of elements using something like items.map(...)
, you should really be assigning a unique key to each element in the list that you're rendering:
{items.map((item, index) => (
<div key={item.get('id')}>item #{index}</div>
))}
the reason is that react does some optimizations here to make rendering (and re-rendering) lists less costly. if it sees a list that used to be composed of keys 0, 1, 2
and you've done some operation to reorder the items in your state, so that now the keys are passed to your map function in the order 0, 2, 1
, it won't rebuild the dom to reflect the changed order, but rather will just swap the dom nodes (which is faster).
this leads to why you don't want to use index
as a key for your elements, unless you know that their order won't change. let's say you used the iteration index as your keys:
{items.map((item, index) => (
<div key={index}>item #{index}</div>
))}
now, if your items change order, they'll be output with the keys in the same order (index 0
will always be the first index, index 1
will always be the second index, and so on) but with different text inside each div. react will do a diff with the real dom, notice that the value of each div has changed, and rebuild that entire chunk of the dom from scratch.
this gets even worse if your list elements include something with state that isn't reflected in the dom, like an <input>
. in that case, react will rebuild the dom, but any text the user has input in those fields will remain exactly where it was! here's an example from robin pokorny that demonstrates what can go wrong (sourced from this article):
score:0
i guess your condition for the if is index % 2 == 1
which shows the heading when index
is an odd number
{index % 2 == 1 && (
<h1>test output/h1>
)}
but in your case, you are writing this if condition within {}. that means, you are now writing the javascript. so, just use the javascript syntax.
if(index % 2 == 1){
return(
<div>
<span dangerouslysetinnerhtml={{ __html: item }}></span>
<h1>test output/h1>
</div>);
}
update: as jaromanda pointed out, you need to return one element. so, wrapping your <span>
and <h1>
into <div>
will gives a single element.
Source: stackoverflow.com
Related Query
- Conditional Statement Within Map Loop
- JSX: Conditional statement within a map
- React conditional statement within a map function
- Switch statement / conditional in map function JS
- Conditional rendering with && operator within react return statement
- useState Hook inside loop or conditional statement
- Conditional statement within foreach?
- removing child component from parent component within map loop
- Second layer of conditional statement within inline condition react
- NEXTJS Conditional Statement not working inside of a map
- Reactjs Looping and Adding Conditional Elements within Loop
- How to iterate through an array of objects with a map function that has a conditional statement inside?
- Render Table <tr> tag based on condition in ReactJs within map loop
- Conditional classes on single instances of component within a loop
- Problems with React.js conditional statement within another conditional statement
- Reusing properties within map loop in ReactJS - best practice
- Loop within return statement or outside the return statement of a functional component?
- React Component not rendering within map loop
- setInterval and useState - Conditional statement using updated state within the interval?
- Conditional Rendering React Bootstrap Columns Within Array Map
- How to CSS display:none within conditional with React JSX?
- How to use if within a map return?
- Using a map within a map in jsx
- loop in return statement of a component in react js
- How to loop inside map function using jsx format React JS
- React Material UI condition statement within style property of button
- react if statement in jsx and map
- React won't render within map function
- Redux-saga select testing with conditional statement
- React JS/JSX if statement in loop
More Query from same tag
- change div background color on click REACT
- Render react component based on dynamic routes
- Why setTimeout is not triggering inside useCallback ReactJS
- Generate select option entries from variables in ReactJs
- Benefits of composition over inheritance in React
- react state change doesn't work as expected
- Redux form props & typescript
- Next.js Unhandled Runtime Error "Failed to load script: /_next/static/chunks/..." only triggered in dev mode
- antd Table onRow onClick to another component
- Get cookie on front-end
- Taking the initial values of an object using useState hook in React
- How to find the data associated with elements in a rendered map
- How to test react component having css transition?
- ReactJS - State object property is null after setState
- React Context API doesn't work when passing null
- How to render JSON data in reactjs?
- How to use classNames library in a function in react?
- Buttons has no background on Safari iOS
- Next.js error adding "sizes" on Image using layout="responsive"
- Conditionally mapping two different arrays into a React component depending on boolean value
- Upgrading React-Router and replacing hashHistory with browserHistory
- How to create a datepicker in react js
- What is the alternative for Redirect in react-router-dom v 6.0.0?
- Drawing SVG shape with mouse using React
- REACT-Native conditional props throwing error
- After fetch state returns undefined
- React route exact not work if I have child route in React router v5
- react google map returns empty element _ react
- Accessing the whole state object in React 16.8
- Change "go back" button label accordingly to the last page visited with react-router-dom