First let’s start off by talking about React. What is React? React is a useful library in Javascript that let’s us build better interactive user interfaces (UI). React was created by Facebook enginerr Jordon Walke. Two featers of React is the use of JSX (think of JSX as a mixture of javascript and html) and the use of a virtual DOM.
Now, let’s talk a little bit about rendering. Rendering lets you transform your React components into DOM nodes so that the browser can read and understand your code and then display it on the screen. In other words, rendering is what puts the code we write onto the UI. React classes are objects that will usually always have a render function. The render function will return a value or list of values that will appear on the screen.
We can now see how to render a list. In the example below we create a class (Cats). In the Cat class object we have our render function that returns a list of cats. This is a very basic way of rendering a list and this example is hardcoding the list. There may be some situations where you may need or want to do this, but in general it is better to render a list dynamically so that the items of the list can be easily changed.
| Var Cats = React createClass({ render: function(){ return ( <ul> <li> Pickles</li> <li> Noodles</li> <li> Pumpkin</li> </ul> ) } }) |
It’s best to render a list dynamically so that it can be easily changed from other parts of your code. Within the class you will want to establish the state. In this example, within the state, we have an object amd I set the value to an array of cats. Within the render we are able to access that array within the state by writing this.state.cats. We then use map to access each value. Using map we can use JSX to get each cat an <li> tag, which creates the list for us. Later, if we need to add a cat or remove a cat from our class, instead of having to go to our render function and change that list, we can access the array in our state and that way all of the information will be updated anywhwere the class and state or references. Where as if we changed the information within the render function, the state would not change and that could potentionally cause bugs in our program.
| import React, { Component } from “react”; class Cats extends Component { state = { cats: [“Pickles”, “Noodles”, “Pumpkin”] }; render() { return ( <ul className=“cat-list”> {this.state.cats.map(cat => ( <li key={cats} className=“list-of-cats” > {cats} </li> ))} </ul> ); } } |
In conclusion, if you need to render a list, it is best to do it dynamically using state. React is a very handy javascript library that allows you to use JSX to help make a funcitonal UI. A big componant of react is the render function and it is very helpful for rendering lists for our apps.