Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Working with conditions & lists in React
Sergio Daniel Xalambrí
Sergio Daniel Xalambrí

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>;}
Enter fullscreen modeExit fullscreen mode

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>  );}
Enter fullscreen modeExit fullscreen mode

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>);}
Enter fullscreen modeExit fullscreen mode

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>);}
Enter fullscreen modeExit fullscreen mode

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>);}
Enter fullscreen modeExit fullscreen mode

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>);}
Enter fullscreen modeExit fullscreen mode

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 theindex 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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
gustavofsantos profile image
Gustavo Santos
human / developer / curious
  • Location
    Curitiba PR, Brazil
  • Education
    Computer Engineer
  • Work
    Senior 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

CollapseExpand
 
chibiblasphem profile image
Debove Christopher
  • Location
    Paris
  • Work
    Frontend Developer at SeLoger
  • Joined

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

CollapseExpand
 
sergiodxa profile image
Sergio Daniel Xalambrí
  • Email
  • Location
    Lima, Perú
  • Work
    Web Developer at Daffy.org
  • Joined

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.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

  • Location
    Lima, Perú
  • Work
    Web Developer at Daffy.org
  • Joined

More fromSergio Daniel Xalambrí

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp