5

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'));
Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142
Ugurcan Omur
  • 73
  • 2
  • 7
  • Possible duplicate of [Deep nested array of objects not rendering](https://stackoverflow.com/questions/45072608/deep-nested-array-of-objects-not-rendering) – Shubham Khatri Aug 14 '17 at 08:50

2 Answers2

16

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

Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142
0

you should return the map function itself, and you can achieve it with es6 single line arrow functions too

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

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

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

  render() {
    return (
      <div>
        <div>blabla</div>
        {this.renderKeywords()}  
      </div>
   );
 }
}
React.render(<Application />, document.getElementById('app'));
hannad rehman
  • 4,133
  • 3
  • 33
  • 55
  • 2
    Your answer doesn't bring anything new to the question and is basically just repeating already accepted answer... – Marek Takac Aug 14 '17 at 09:06
  • i have updated the es6 arrow function which is the actual implementation of it when you are directly returning something from it. @MarekTakac – hannad rehman Aug 14 '17 at 09:46