Naveen DINUSHKA
Naveen DINUSHKA

Reputation: 1627

Cannot read property 'map' of undefined reactjs when i have declared the property already

Hi I am running the following , I have set textfield property to a string and as far as I know thats an array and map functions should work on arrays but it still says Cannot read property 'map' of undefined, well Is it not defined in there in the state? Thanks

class App extends Component {

  state={
    textfield:"first value", 
  }

makeUnique =(textfield)=>{
  return String.prototype.concat(...new Set(textfield) );
}

  textchanged = (event)=>{
    this.setState({
      textfield:event.target.value,
      caltexlength:event.target.value.length,    
    })    
  }


  render() {
    let uniquechars=null;

    uniquechars=(<div>
      {
        this.textfield.map((char,index)=>{
          return <charComponent
          char ={this.makeUnique(this.state.textfield)}/>
        })
      }
    </div>)## Heading ##

Upvotes: 0

Views: 47

Answers (3)

Vishmi Money
Vishmi Money

Reputation: 144

Write the line this.textfield.map((char,index) as below.

[...this.state.textfield].map((char,index)

With the spread operator you will create an array from your string and you can call map on it.

Upvotes: 1

Ilya Lesik
Ilya Lesik

Reputation: 264

You have to replace

this.textfield.map

to

this.state.textfield.split('').map

Upvotes: 1

Hemadri Dasari
Hemadri Dasari

Reputation: 34014

TextField is a string so why are you doing map on it. Map works only on arrays. To access state TextField it should be this.state.textField but not this.textField

So change

uniquechars=(<div>
  {
    this.textfield.map((char,index)=>{
      return <charComponent
      char ={this.makeUnique(this.state.textfield)}/>
    })
  }
</div>)

To

uniquechars=(<div>
   <charComponent
      char ={this.makeUnique(this.state.textfield)}/>
</div>)

Upvotes: 1

Related Questions