Frontend
.......................................................................................................
Signup to be notified when the Fluent React course
launches in MARCH 2025 .
(and get started with a 5-part free React course in the mean time.)
...........................................................................................

What's JSX?

JSX is "JavaScript XML". It is an extension of the JavaScript language that lets you to write both HTML-like markup and JavaScript code side by side.
 
In React, JSX is used as the "markup" language to develop and style the UI of the custom components you will be creating for your app.

 

In this cheatsheet, we will be looking at some JSX use cases and how to implement them in as few lines of JSX as possible.

 

Use this cheatsheet as a quick reference guide for when you need to write your React component's markup.

 

Setup for this Cheatsheet

While we work through code for this cheatsheet, I will be using a trusty `ExamplePost` component.
 
So, here we go ...

Render a Piece of Component Data

A variable/(piece of data) in a React component can be one of:
  • A piece of state local to the component, such as the `firstName` state in a `UserDetails` component.

  • A prop passed to a component from a parent component. For example, if you are rendering the `UserDetails` component inside a parent `ListOfUsers` component, you may be passing the `user` object from the (parent) `ListOfUsers` component to the (child) `UserDetails` component.

  • A variable defined locally in the current component's function. For example, you can define a "favoriteBooks" array in the component. You will then render this array in the JSX/UI of the component.
In either case, the variable will be rendered the same way inside the JSX.

Here's an example with all 3 types of component data

 


import React, {useState} from 'react'

const ExamplePost = () => {
    const [firstName, setFirstName] = useState('Muhammad')
    const [lastName, setLastName] = useState('Jalloh')

    const bioObj = {
        dept: 'Engineering',
        desc: 'Responsible for conceiving, developing, deploying and maintaining the platform.'
    }

    return (
<div> 
<h4> User Bio Data </h4> 
<p> First Name: {firstName} </p> 
<p> Last Name: {lastName} <p> 
<p> This user is part of the {bioObj.dept} team and is: {bioObj.desc} </p> 
</div> 

    )
}

export default ExamplePost

You will notice that, when rendering a JavaScript object (which these are), you have to enclose them in a pair of curly { } braces in the JSX markup.

This makes JSX look like a templating language, like Jinja or Mustache, if you are used to using one.

 

Render a JavaScript Expression

This is not always useful, but it comes in handy in some use cases.

Imagine you are working on an component that requires a lot of computational logic inside the component (such as a financial application, etc.), you can decide to handle much of that computation inline in the component.

 

Any JavaScript code you want to render in the JSX markup __must__ be enclosed in pair of curly { } braces.

 

To render a JavaScript expression, enclose it in a {} pair also, like this:

{
    firstName ? alert(`My name is ${firstName}`)
    : alert(`I don't have a name yet.`)
}

<p>
    {`${firstName} was born ${3 * 5} years ago.`}
</p>
It is a silly example, but the point is that you can render a simple JavaScript expression onto the UI by enclosing it in a pair of curly { } braces.

 

Style an Element

While developing your React components, you can use styling in one of 4 ways:
1. Refer to a CSS class using the `className` attribute

<h3 className='text-primary'> My Title </h3>

This will give the text of the tag a blue color using the Bootstrap `text-primary` CSS class.

 

2. Define your CSS inline

 

You can do this like this:


<h3 style={{ color: 'blue'}}> My Title </h3>

You will get the same effect (i.e blue text) as above.

 

3. Create a style object (in JavaScript) and use it in your JSX.
 
In this case, you will create a JavaScript style object outside the component's `return()` statement (where your JSX will go). You will then reference your style object using the `style` attribute of the JSX tag you are styling.

 

This works like this:

import React from 'react'

const Profile = () => {

    const memberStuff = [
        {name: 'Books', link: '/books'},
        {name: 'Journals', link: 'journals'},
        {name: 'Magazines', link: 'mags'},
        {name: 'Special Offers', link: 'offers'},
        {name: 'Downloads', link: 'downloads'}
    ]

    const stuffStyle = {
        color: 'green',
        marginTop: '15px',
        // Add as many CSS styles as you want here.
    }
    
    return(
            <>
                <h5 style={{ margin: '25px'}}> Members-Only Stuff </h5>
                <div>
                    These are your members-only stuff.
                    
                    <ul>
                        {memberStuff.map(item => (
                            <li key={item.link} style={stuffStyle}>
                                <a href={`members/${item.link}`}> {item.name} </a>
                            </li>
                        ))}
                    </ul>
                </div>
            </>     
    )
  
}

export default Profile

4. Dynamically-define your styles (inline, using a style object or by referencing a CSS class) based on a piece of logic/condition that must be satisfied.


<h3 className={firstName ? 'text-success' : 'text-danger'}> My Title </h3>
This will assign the `text-success` (i.e "green") CSS class to the `h3` tag's text if the `firstName` state has a value; otherwise, the `h3` tag's text will be assigned a `text-danger` (i.e "red") CSS class.
 
You can do the same dynamic styling using the `style` attribute, like this:


<div> <h3style={{color:firstName ? 'green': 'red'}}> My Second Title </h3></div>

Reference an External Function

You can reference a function from inside your JSX markup.

 

This usually happens when:
  • your component is passed an external function (as a prop from a parent component, state manager, etc.)

  • you define an event handler (function) in your component
If your component is passed a function as a prop, you can handle it this way:

import React from 'react'

const ExamplePost = (props) => {

  return (
    <div>
        <button onClick={props.doSomething}> Click Me </button>
    </div>
  )
}

export default ExamplePost

If you define an event handler function in your component, you can reference it in your JSX markup, like this:

import React from 'react'

const ExamplePost = () => {
    const doSomething = () => {
        console.log(`do something here...`)
    }

  return (
    <div>
        <button onClick={doSomething}> Click! </button>
    </div>
  )
}

export default ExamplePost
A more practical use of referencing a function is when it comes to event handling during form processing, as we will see shortly.

Write Inline and External Functions to Handle a Form Input

When a user interacts with your form, you should use the input to set a piece of the component's state. What you do with it afterwards (submit the form via an API call, render additional/subsequent form fields, etc.) depends on the needs of your component.
 
Here's how to write an inline function to handle a user's input on a form. We also cover how to use a function (external to the JSX/outside the JSX) to handle the form submission logic.

import React, {useState} from 'react'

const ExamplePost = () => {
    const [userName, setUserName] = useState('')
    const [userEmail, setUserEmail] = useState('')

    function submitForm(e){
        e.preventDefault()

        if(userName && userEmail){
            // Ideally, you will make an API call to submit the form data here
            // But we will settle for a console.log() and an alert()
            console.log(`${userName}: ${userEmail}`)
            alert(`Thanks, ${userName}`)
            // Clear/reset all the form fields
            setUserName('')
            setUserEmail('')
        }

    }

  return (
    <div>
        {/* The <form>'s onClick listener is referencing the submitForm() function defined above. */} 
      <form onSubmit={submitForm}> 
      <input type='text' value={userName} placeholder='Your User Name' 
      // The onChange listener is passed an inline JS function 
      onChange={(e) => setUserName(e.target.value)} /> 
      <input type='email' value={userEmail} 
      // The onChange listener is passed an inline JS function 
     onChange={(e) => setUserEmail(e.target.value)} 
     placeholder='Your Email' /> 
     <button type='submit'> Submit </button> 
     </form> 
     </div> 
     ) } 
    export default ExamplePost

In this example, the `<input />` elements' `onChange` event listener is passed an inline JavaScript function to enable it update the associated component states: `userName` and `userEmail`.

 

The form itself references the `submitForm()` function defined in the component's body.

 

You could have written the event handler functions for the `<input />` elements as external functions (just like the `submitForm()` handler function) and then reference them in the same way (as you did with the `submitForm()` function from the `<form>` element.)

Render an External Element in the JSX

There may be cases where you want to make the JSX code in your component's `return()` statement as little, simple and as clean as possible.

 

There are two ways to achieve this:
 
a. Create child components to handle some of the logic and UI of the current/parent component.

 

b. Create UI elements in the current component and then render them in the body of the component as needed.

 

Let's look at how to implement some mini-components (aka "elements") inside a React component:


import React, {useState} from 'react'

const Profile = () => {
    const [userIsLoggedIn, setUserIsLoggedIn] = useState(false)
    
    const memberStuff = ['Books', 'Journals', 'Magazines', 'Special Offers']

    const memberUI = () =>  (
        <div> 
            <h5 style={{ margin: '25px'}}>  Members-Only Stuff </h5> 
            <div> 
                These are your members-only stuff.
                
                <ul> 
                    {memberStuff.map(item =>  (
                        <li key={item}> 
                            {item}
                        </li> 
                    ))}
                </ul> 
            </div> 
        </div> 
    )

    const unregisteredUI = () =>  {
        return(
            <> 
                <h5 style={{ margin: '25px'}}> These are our Free-for-all Stuff </h5> 
                <div>>
                    <p> 
                        We currently don't have stuff for non-registered members.
                    </p> 
                    <p> 
                        Please, <a href='#'> register </a>>and login to access the members-only stuff.
                    </p> 
                </div> 
            </> 
        )
    }

    return(
        <> 
            {userIsLoggedIn ? (
            <> 
                {memberUI()}
            </> 
            ): (<> {unregisteredUI()} </> )}
        </> 
    )

}

export default Profile

Play with switching the `userIsLoggedIn` state from `true` to `false` and see the component render the associated element in the browser window.

 

You will notice that when you define an element, you can return it:
  • implicitly: by returning it inside a pair of `()` parentheses, like we did with the `memberUI` element in this example.

  • explicitly: by returning it inside the `return()` statement of the function that defines the element, such as what we did with the `unregisteredUI` element in this example.
Gotcha Alert: If you don't include the pair of `()` parentheses when you call the element in the JSX, like the following

return(
        <>
            {userIsLoggedIn ? (
            <>
                {memberUI}
            </>
            ): (<> {unregisteredUI} </> )}
        </>
)

you will get a warning:

Warning: Functions are not valid as a React child.
in the browser console and your component won't render. So, always include those pairs of `()` parentheses.
So render { memberUI() } and { unregisteredUI() } and not { memberUI } and {unregisteredUI} (like we did in the example above.)

Loop Through and Render an Array of Elements

You have already seen how to do this in the previous example. I will enhance and replicate it here, just to explain some concepts:

import React, {useState} from 'react'

const Profile = () => {
    const [userIsLoggedIn, setUserIsLoggedIn] = useState(false)
    
    const memberStuff = [
        {name: 'Books', link: 'books'},
        {name: 'Journals', link: 'journals'},
        {name: 'Magazines', link: 'mags'},
        {name: 'Special Offers', link: 'offers'},
        {name: 'Downloads', link: 'downloads'}
    ]
    
    return(
        <div>
            {userIsLoggedIn && (
                <>
                    <h5 style={{ margin: '25px'}}> Members-Only Stuff </h5>
                    <div>
                        These are your members-only stuff.
                        
                        <ul>
                            {memberStuff.map(item => (
                                <li key={item.link}>
                                    <a href={`members/${item.link}`}> {item.name} </a>
                                </li>
                            ))}
                        </ul>
                    </div>
                </>
            )}
        </div>
    )
}

export default Profile

When looping through and rendering an array, always:
  • Make sure that each item is returned as an element. That is, the returned expression must be enclosed in a JSX tag. If the expression needs multiple JSX tags, make sure there is a parent/root element that is returned (with all the other JSX tags enclosed in it.) This root element could be a Fragment (`<Fragment> </Fragment>` or `<> </>`) or an actual tag like a `<div></div>` or the `<li></li>` that we used here.

  • Each item must have a `key` prop with a unique identifier value. In this example, we used the `item.link` property as the unique identifier passed to the element's `key` prop. The `item.name` value could also work if it is unique in every item in the array.

  • Render the value(s) of the item in a pair of curly `{}` braces (as we did `{item.link}` and `{item.name}`, in this example).

Render an `if…else ` Logic in the UI

There are two forms of conditional rendering you can have in your component's JSX:
    1. `if(true){ render_this }`: If a condition is true, render the following markup. Implicitly, if the condition is false, do nothing ... and render nothing.
      In this case, you set the condition and pass the element to be render after a pair of `&&` ampersands.

       

      This can be implemented as such:
      
      {userIsLoggedIn && (
          <p> You are logged in. </p>
      )}
      
      
      Note that the element that is rendered after the `&&` must be enclosed in a pair of `()` parentheses which contains a root element to be returned.

    2. if(true){ render elementA }else{ render elementB }`: In this case, you have two elements (i.e pieces of JSX markup); one is rendered if the set condition is true, while the other element is rendered if the condition is false.

       

      Extending the example above, we can implement this like this:
      
      {userIsLoggedIn ? (
          <div>
              <p< You are logged in. </p>
              <p< More JSX markup can go here. </p>
          </div>
      ): (
          <div>
              <p> You are not logged in. </p>
              <p< Even more JSX markup can go here. </p>
          </div>
      )}
      

What's Next?

Now, that you have the basics of how to write proper JSX markup for your React app's components, what's next?
 
Well, a few things are in order here:
 
  • Create a fresh React app. You can model it after one you find on GitHub or Youtube or somewhere else. If you are lost for ideas, check out this list of (progressively more complex) apps you can build that I outlined in the [`How to Learn React` guide]().

  • Learn to read the warnings and errors you get in the browser console and your terminal so that you can get used to knowing what bug your code has triggered and where/how to solve it.

  • Document your bugs and their solutions. They will save you many developer hours as you progressively tackle more (complex) apps.

  • Document how you solved these bugs and put that in a cheatsheet of your own for quick "debugging" reference.

  • Rinse and repeat the above three steps until you can write JSX in your sleep. So, maybe not dream in JSX. But, at least, become very skilled in it.
Now, get coding and build an app that changes the world for the better.

Developer Guides Related to This One:

Please, share your insights, concerns and experiences about the topic and/or content of this article.