I have a React.JS component that will map the notes
variable to display.
However, I have run into the problem of having no notes and receiving an error. What is a proper way to approach this?
Here is the code:
import React, {Component} from 'react'; class List extends Component { constructor(props){ super(props); } render(){ var notes = this.props.items.map((item, i)=>{ return( <li className="listLink" key={i}> <p>{item.title}</p> <span>{item.content}</span> </li> ) }); return( <div className='list'> {notes} </div> ); } } export default List;
In React, the map method is used to traverse and display a list of similar objects of a component. A map is not a feature of React. Instead, it is the standard JavaScript function that could be called on an array. The map() method creates a new array by calling a provided function on every element in the calling array.
To check if an array is empty in React, access its length property, e.g. arr. length . If an array's length is equal to 0 , then it is empty. If the array's length is greater than 0 , it isn't empty.
You are correct, forEach doesn't return anything, use map instead, it will return an array of JSX components.
Simply map items as you usually do from one array. With that, use the CSS property "columns" to display them as described in the question above. Assuming two column's, having col-md-6 class for row splitting.
If you want to render the notes when at least one note exists and a default view when there are no notes in the array, you can change your render function's return expression to this:
return( <div className='list'> {notes.length ? notes : <p>Default Markup</p>} </div> );
Since empty arrays in JavaScript are truthy, you need to check the array's length and not just the boolean value of an array.
Note that if your items
prop is ever null, that would cause an exception because you'd be calling map
on a null value. In this case, I'd recommend using Facebook's prop-types library to set items
to an empty array by default. That way, if items
doesn't get set, the component won't break.
here is the simplest way to deal with
import React, {Component} from 'react'; class List extends Component { constructor(props){ super(props); } render(){ var notes = this.props.items?.map((item, i)=>{ return( <li className="listLink" key={i}> <p>{item.title}</p> <span>{item.content}</span> </li> ) }); return( <div className='list'> {notes} </div> ); } } export default List;
just try to add "?" for the array that you maped
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With