e.preventDefault() is not a function in Reactjs, bind used

Viewed 307

I'm new to react, i want to pass an a value as an argument when the user clicks, and also preventDefault, i found this question that suggest using bind i used it as the code below but didnt solve my problem, it gave me the error TypeError: e.preventDefault is not a function.


  constructor(props){
    super(props)
    this.state={
      headline:'',
      articles:[],
      article:[],
    }
  }


componentDidMount(){
  axios.get("http://127.0.0.1:5000/api/v1/news")
  .then(res=>{this.setState({articles:res.data})}
  )
}




browse = (e,id) => {
  console.log(e)
  e.preventDefault()
  console.log(id)
  axios.get("http://127.0.0.1:5000/api/v1/news/"+id)
  .then(res=>{this.setState({article:res.data,});console.log(res.data)})
}

Here's where i use the browse method

  {this.state.articles.map(art=> {return (
                     <tr>
                    <td><a href={art.url}>{art.headline}</a></td>
                    <td>{art.topic}</td>
                    <td>{art.author}</td>
                    <td><button  onClick ={this.browse.bind(this,art._id.$oid)} > Browse </button></td>
                                            </tr>
                                      )})}

Here's the error

×
TypeError: e.preventDefault is not a function
App.browse
src/App.js:36
  33 |         }
  34 | 
  35 | browse = (e,id) => {
> 36 |   e.preventDefault()
  37 |   axios.get("http://127.0.0.1:5000/api/v1/news/"+id)
  38 |   .then(res=>{this.setState({article:res.data,});console.log(res.data)})
  39 | }
View compiled

1 Answers

Actually, by writing onClick in that way, you are calling the function as the component is rendered and the passed "e" is not the event, so e.preventDefault() is not a function.

For binding onClick without calling it at the runtime and passing "event" you can use the following format as mentioned here:

onClick={(e) => this.browse(e, id)}
Related