+ 2

react js..help..

i found this code return (<ul> {this.state.list.map(e => { return <li key={e}>{e}</li>})} </ul>) people said that "{}" in jsx is to interpret the code inside it as javascript, since "this.state.list.map" is already inside a curly bracket,why do we need to wrap the "e" variable inside another curly bracket again = {e}? doesnt it already interpreted as javascript variable since it already inside a cruly bracket?

5th Apr 2020, 12:50 PM
durian
durian - avatar
4 odpowiedzi
+ 8
The curly brackets in between the <li>{e}</li> are there in order to get the evaluated value of e. Without them you will get the letter 'e' as a string. you only need those curly brackets because e is wrapped in a HTML element
5th Apr 2020, 4:00 PM
Burey
Burey - avatar
+ 3
In order to understand JSX, we need to study from a simple example, const List = <ul><li>Item 1</li></ul>; This would create a List component with html code of <ul><li>Item 1</li></ul> Notice that List is not equal to string "<ul><li>Item 1</li></ul>" nor it's a HTML. It's a JSX code, babel transpiler would be needed to transpile it to HTML code. Jsx code can be inserted with javascript variables with {} notation. So we can write const item = "Item 1"; const List = <ul><li>{item}</li></ul>; if in array variables: const items = ["Item 1", "Item 2"]; const List = <ul> <li key={0}>{items[0]}</li> <li key={1}>{items[1]}</li> </ul>; We can also populate the array data using map method: const items = ["Item 1", "Item 2"]; const List = <ul> { items.map(( e,i ) => { return <li key={i}>{e}</li> }) } </ul>; Notice that the return function in fact returns a jsx code (not string, without double quotes "), thus it needs {} in order to insert js variables into jsx.
6th Apr 2020, 4:06 PM
Calviղ
Calviղ - avatar
+ 3
The map method can be further simplified to const List = <ul> {items.map(( e,i ) => <li key={i}>{e}</li>) }</ul>;
6th Apr 2020, 4:08 PM
Calviղ
Calviղ - avatar
+ 1
tq..i got it now
7th Apr 2020, 4:25 AM
durian
durian - avatar