Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 array map doesn't return anything: ReactJS

I have an array and i have a simple string value. I want to mapping my array because i'm try to find my string value.

I have a code like this, but map function doesn't return anything :/

class Application extends React.Component {
  constructor(){
    super();

    this.state = {
      questionAnswer: 'is that possible',
      question: ['is', 'possible', 'that']
    }  
  }

  renderKeywords() {
    this.state.question.map((item, key) => {
      return (
        <span>{item}</span>
      );
    }); 
  }

  render() {
    return (
      <div>
        <div>blabla</div>
        {this.renderKeywords()}  
      </div>
   );
 }
}
React.render(<Application />, document.getElementById('app'));
like image 980
Ugurcan Omur Avatar asked Aug 14 '17 08:08

Ugurcan Omur


1 Answers

Because you are not returning anything from renderKeywords method, you are returning from map body only. If you don't return anything from function then by default it will return undefined, you need to return the result of map (array of elements).

Like this:

renderKeywords() {
    return this.state.question.map((item, key) => {   //here
        return (
            <span key={key}> {item} </span>
        );
    }); 
}

In short you can write it like this:

renderKeywords() {
   return this.state.question.map((item, key) => <span key={key}> {item} </span> ); 
}

Suggestion:

Assign unique key to each element.

Check this answer for more details about key: Understanding unique keys for array children in React.js

like image 177
Mayank Shukla Avatar answered Nov 03 '22 19:11

Mayank Shukla