2

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 Answer 1

1

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)}
Sign up to request clarification or add additional context in comments.

5 Comments

with this is not telling preventDefault is not exist, but still reload the page.
please test putting the line "e.preventDefault()" at first before the "console.log(e)" and let me know about the result
why are you calling the "this.componentDidMount();" again? everything seems to be working fine for me
i just added it, because when it reloads. it gives an error of the this.state.articles that is not there. can i do this other way?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.