Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS form submit preventdefault not working

I'm in the process of learning React JS, while following an online tutorial. The below code stopped working and gives me an exception "TypeError: Cannot read property 'PreventDefault' of undefined". Can someone please help me understand the reason causing this? Thanks in advance.

const Card = (props)=>{
  return(
        <div style={{margin:'1em'}}>
          <img width ="75" src ={props.avatar_url}/>
          <div style={{display: 'inline-block', marginLeft: 10}}>
             <div style ={{fontSize:'1.25em', fontWeight: 'bold'}}>
               {props.name}
             </div>
             <div>{props.company}</div>
          </div>
        </div>
       );
};

const CardList = (props) => {
    return (
            <div>
                {props.cards.map(card => <Card {...card} />)}
             </div>
           );
       }

class Form extends React.Component {

  handleSubmit = (e) => {
        e.PreventDefault();
        console.log('Event: Form Submit');
  };

  render() {
        return (
        <form onSubmit={this.handleSubmit()}>
        <input type ="text" placeholder ="Github username"/>
        <button type ="submit">Add Card</button>
      </form>
    );
  }
}

class App extends React.Component {

state = {
    cards:  [
        {       name : "Paul O’Shannessy" , avatar_url: "https://avatars1.githubusercontent.com/u/8445?v=4", company: "Facebook"  },
        {       name : "Ben Alpert" , avatar_url: "https://avatars1.githubusercontent.com/u/6820?v=4",company: "Facebook"  },
      ]
}

  render() {
        return(
            <div>
              <Form />
              <CardList cards={this.state.cards} />
            </div>
        );
  }
}

ReactDOM.render(<App />,mountNode)
like image 894
user2066540 Avatar asked Dec 02 '22 11:12

user2066540


1 Answers

Two small problems here. First one, it is not PreventDefault, it is preventDefault. Then here:

<form onSubmit={this.handleSubmit()}>

You are not using a callback function instead, you are invoking the real function. If you don't use a callback, you can't get the e. Also, if you use it like above, it fires in the first render but never fires again with a submit.

<form onSubmit={() => this.handleSubmit()}>

But, you don't need to and shouldn't use it like this. If you use it like this, the callback function will be recreated in every render. Just use the function's reference. You can get e with this, too.

<form onSubmit={this.handleSubmit}>

One last thing, use a key for your Card's map.

{props.cards.map( card => <Card key={card.name} {...card} /> )}

Oh, maybe one last thing :) Use a linter if you don't use it currently.

like image 170
devserkan Avatar answered Dec 24 '22 17:12

devserkan