A C# Developer’s Guide to: ReactJS – Part 3 – Conditionally Rendering HTML in React

This is the third in a series of posts on interesting things I’ve discovered about React; the first of these can be found here.

One of the things that tripped me up early on while I was learning React (not that I’m a fully-fledged expert now or anything) was how to display HTML elements based on a given criteria. For example, say you only want to display a label while the form is loading, or you want to display a message based on other information on the screen.

If you were using a desktop binding architecture, say MVVM, you would bind the visibility to a visible property. Likewise in HTML, you may have a conditional style based on the bound model property. Let’s see how you might do that in React.

Create a new React Application

Let’s start by creating a new React application (using bash here):

This isn’t a particularly fast process, so maybe it’s time to get a brew.

Once it’s done, and assuming you have VS Code installed (if you don’t then go and install it from here), type:

code testreactapp

And as if by magic, VS Code appears!

You should be able to run this straight out of the box. Start a new terminal in VS Code, and type npm start:

The displayed screen is of a little animated spiragraph. Let’s add a button and, where the user presses the button, hide or show the spinning spiragraph.

State

As I have previously written about here state is one of the key concepts in React. Let’s create a state object that will determine the visibility of our animation.

In order to introduce state, we need to change the default app.js to be a class, as functions cannot have state. Note that, were this a real application, you would probably move this out into a separate component; but let’s change our app.js to be a class:

import React, {Component} from 'react';
import logo from './logo.svg';
import './App.css';

export default class App extends Component {
	render() {
		return (
			<div className="App">
				<header className="App-header">
					<img src={logo} className="App-logo" alt="logo" />
					<p>
						Edit <code>src/App.js</code> and save to reload.
					</p>
					<a
					className="App-link"
					href="https://reactjs.org"
					target="_blank"
					rel="noopener noreferrer"
					>
						Learn React
					</a>
				</header>
			</div>
		);
	}
}

All I’ve done here is change the function to a class, and added `import {Component}`.

Now let’s add some state. At the top of the class, add a constructor:

constructor(props) {
	super(props)
	this.state = {
		showSpiragraph: true
	}
}

Let’s now add the button, so we can change the value of the state; first, we’ll need the button itself:

. . .
	<a
		className="App-link"
		href="https://reactjs.org"
		target="_blank"
		rel="noopener noreferrer"
	>
		Learn React
	</a>
	<button onClick={this.toggleShow}>Hide/Show</button>
</header>
. . .

Then the function that we’re calling (toggleShow):

toggleShow = () => {
  this.setState(state => ({showSpiragraph: !state.showSpiragraph}));
}

If you run this now, it will allow you to press the button until your finger aches, but it won’t actually do anything.

Conditionally Displaying an Element

Okay, so we come to the crux of the entire post; we can conditionally render our image by using the following syntax:

. . .
<header className="App-header">
  {this.state.showSpiragraph &&
    <img src={logo} className="App-logo" alt="logo" />
  }
. . .

You should now be able to click the button and have the Spiragraph show and hide at will.

References

https://medium.freecodecamp.org/quick-guide-to-understanding-and-creating-reactjs-apps-8457ee8f7123

https://reactjs.org/docs/handling-events.html

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.