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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With