
Posted on • Edited on • Originally published atsergiodxa.com
Working with conditions & lists in React
In a previous article I wrote abouthow to start a React project using the state and effect hooks, this time we will see how to work with conditions, lists and forms in React.
Conditional Rendering in React
Let's start talking about conditional rendering, multiple times you will need to render something in React based on a condition and if the condition isfalse
render a different thing. To do so we have multiple options.
Using a Normalif
The easiest way is to use a normalif
inside our component code and return inside and outside theif
.
constSpinner=()=><strong>Loading...</strong>;functionMyComponent({isLoading}){if(isLoading)return<Spinner/>;return<main>Thisistherealcontent</main>;}
In our component ifisLoading
is true we will return the component<Spinner />
but ifisLoading
is false we will render the<main>
with some text inside.
Switching Only Content Using Ternaries
Another option is to use ternaries directly inside the returned elements. This is specially useful if you want to render some content always and only do the changes in a specific area.
functionMyComponent({isActive}){return(<main>I'm <strong>{isActive ? "active" : "inactive"}</strong> </main> );}
In this case it will return the<main>
and theI'm
all the time, inside a strong it will returnactive
orinactive
based on the condition, if we don't use JSX we need to return those values as strings inside quotes instead of the text directly, this is because inside the curly brackets we use normal JavaScript code and not JSX.
Switching Elements Tree Using Ternaries
We could also use ternaries to render different elements based on conditions.
constSpinner=()=><strong>Loading...</strong>;functionMyComponent({isLoading}){return(<main><h2>Thisismyapp</h2>{isLoading?<Spinner/>:<article>Thisistherealcontent</article>}</main>);}
This is similar to the examples above, we will always have themain
andh2
tags but we will render the<Spinner />
ifisLoading
istrue
and andarticle
with certain content ifisLoading
isfalse
. Unlike the previous example we don't need to wrap the content in quotes because we wrote it inside JSX code so we recover that capability as in theh2
.
Rendering an Element or Null
There is also another possible case where you need to render an element or nothing, again there are a few options.
Using a Ternary
The first one is using a ternary to render the element ornull
.
constSpinner=()=><strong>Loading...</strong>;functionMyComponent({isLoading}){return(<main><h2>Thisismyapp</h2>{isLoading?<Spinner/>:null}<article>Thisistherealcontent</article></main>);}
In this case ifisLoading
istrue
it will render the<Spinner />
but if it'sfalse
it will rendernull
. If we usenull
inside our JSX React will ignore it and avoid rendering in the position.
Using an Implicit Null
We could leverage JavaScript to have implicitnull
in our JSX, technically is afalse
which will also be ignored by React but is similar to the example above.
constSpinner=()=><strong>Loading...</strong>;functionMyComponent({isLoading}){return(<main><h2>Thisismyapp</h2>{isLoading&&<Spinner/>}<article>Thisistherealcontent</article></main>);}
IfisLoading
istrue
JavaScript will execute the next part of the condition where we return<Spinner />
, but ifisLoading
isfalse
it will stop the condition there and returnfalse
, the result is similar to the example above but we don't need to use anull
there.
Lists in React
Now let's talk about working with list, if we have an array of element we could useArray#map to transform the elements to React elements, before such transformation we could use other array methods such asArray#filter, Array#sort, etc. As far they return a new array we could keep adding more and eventually map to React elements.
functionList(){constmessages=[{content:"Lorem",id:1},{content:"Ipsum",id:2},{content:"dolor",id:3},{content:"Sit",id:4},{content:"Amet",id:5}];return(<ul>{messages.filter(({content})=>content[0]!==content[0].toLowerCase()).map(message=>(<likey={message.id}>{message.content}</li>))}</ul>);}
If we review the example above it's possible to see the propkey
which is equal to eachmessage.id
, thiskey
is not an attribute of theli
tag, it is something we need to define when rendering lists on React.
This key lets React identify each item of the list by someimmutable value, the immutable part is specially important, the value should never change and if it does React will treat it as a different element and force a new render.
In case our list is filtered or sorted the key will help React identify each element in their new positions and reduce the DOM updates to the minimum.
Tip: Avoid using the
index
as key, while it works if the list is filtered or sorted it will cause the key value to change to the new index and React will consider them different elements and repaint the whole list.
Top comments(3)

- LocationCuritiba PR, Brazil
- EducationComputer Engineer
- WorkSenior Software Engineer at Loggi
- Joined
Particularly I'd avoid using ternary inside jsx. It scales very well and soon your components will be full of ternaries and the mess will be everywhere

What do you advise to use then ? Ternary is expression and inside jsx expressions are the only way to do condition
Btw don't tell me to create a function which do the condition, that's really dirty. Well coded the use of ternary does not turn your code a mess.
Note that this is only my opinion

I think if you reach the point of having a lot of ternaries or too much nested ternaries, maybe, that component should be split in multiple components because the original one becomes too complex.
But most of the time ternaries are not a problem IMO and you can use them without issues, most probably before you reach the point ternaries are a problem you have another problem and already split the component.
For further actions, you may consider blocking this person and/orreporting abuse