I have an input that after the user inserts a text I want to show each word in a button in button-group
. I split the sentence and map it that returns
There are 2 things you need to know / be aware of :
1 - If you have an array of jsx , for instance :
let arrayOfJsx = [ <div>Hello</div>, <div>World</div> ]
When you put this array in your render method , like :
render(){
let arrayOfJsx = [ <div>Hello</div>, <div>World</div> ]
return (
<div> { arrayOfJsx } </div>
)
}
is equivalent to
render(){
return (
<div>
<div>Hello</div>
<div>World</div>
</div>
)
}
2 - Diffence between Array.prototype.forEach and Array.prototype.map :
When you use forEach, what you return from the function you are passing to forEach is not important, it is only important to know that the function stops executing when you return a value, this is not special to forEach. But when we say what you return is not important we want to point out how what you return is important for Array.prototype.map :
You want to use map when you want to create an array from what you return for each item in an array.
Example :
let a = [ 1,2,3 ]
let b = a.map( item => item + 1 )
// b is now [ 2,3,4 ]
To sum up, what you want to do in your example create an array from map and put it in your render method. If you don ' t know about these 2 points, you won't be understanding how it works.
NOTE : you need to pass a unique key for each item you return in your map function. For instance :
let a = [ 1,2,3 ]
let arrayOfJsx = a.map( item => <div key={item} > I am { item } </div> )
So that react doesn t complain
try this
mapArrayToButtons(){
const buttons = this.state.textArr.map((word)=>{
console.log('the word: ',word);
return(<button key={word} type="button" className="btn btn-default" value={word}>{word}</button>);});
return buttons;
}
You will need to return a value from your function like so:
mapArrayToButtons(){
return this.state.textArr.map((word)=>{
return(<button key={word} type="button" className="btn btn-default" value={word}>{word}</button>);});
}
Hope that helps!