react · React Basics
What will happen if the following render() method executes?
render(){
let langs = ["Ruby","ES6","Scala"]
return (<div>
{langs.map(it => <p>{it}</p>)}
</div>)
}Answers
- Displays the list of languages in the array
- Error. Cannot use direct JavaScript code in JSX
- Displays nothing
- Error. Should be replaced with a for..loop for correct output
{langs.map(it =>
)
}
```
Here, the curly braces (`{}`) in JSX are used to embed JavaScript expressions. The `langs.map()` call in the curly braces is a JavaScript expression which iterates over each item in the `langs` array.
## Displaying an Array of Data in JSX
As per the React best practice, arrays or lists of elements must contain a unique "key" prop. This "key" prop is necessary for React to identify each element in the list. However, since the code in the quiz question does not use a key prop, it doesn't follow this best practice.
Here is how you should ideally translate an array into a list of JSX components using `map()`, while including a 'key' prop:
```jsx
render() {
let langs = ["Ruby","ES6","Scala"]
return (
{it}
)}
{langs.map((it, index) =>
)
}
```
In this modified code, the `index` parameter is the second parameter of the `map()` callback and its value is the index of the current element in the array. It acts as a unique identifier for each paragraph tag created through mapping.
## Conclusion
The `render()` method, JSX, and JavaScript's `map()` function are fundamental React concepts for displaying lists of data. Always remember to incorporate the 'key' prop when rendering lists for optimal performance of your React applications.
{it}
)}