Events - Fundamentals
- Vanilla JS
const btn = document.getElementById('btn');
btn.addEventListener('click', function (e) {
// access event object
// do something when event fires
});
- similar approach
- element, event, function
- again camelCase
const EventExamples = () => {
const handleButtonClick = () => {
alert('handle button click');
};
return (
<section>
<button onClick={handleButtonClick}>click me</button>
</section>
);
};
*most common
*
- onClick (click events)
- onSubmit (submit form )
- onChange (input change )
function BookList() {
return (
<section className='booklist'>
<EventExamples />
{books.map((book) => {
return <Book {...book} key={book.id} />;
})}
</section>
);
}
const EventExamples = () => {
const handleFormInput = () => {
console.log('handle form input');
};
const handleButtonClick = () => {
alert('handle button click');
};
return (
<section>
<form>
<h2>Typical Form</h2>
<input
type='text'
name='example'
onChange={handleFormInput}
style={{ margin: '1rem 0' }}
/>
</form>
<button onClick={handleButtonClick}>click me</button>
</section>
);
};
Event Object and Form Submission
const EventExamples = () => {
return (
<section>
<form>
<h2>Typical Form</h2>
<input
type='text'
name='example'
onChange={(e) => console.log(e.target.value)}
style={{ margin: '1rem 0' }}
/>
</form>
<button onClick={() => console.log('you clicked me')}>click me</button>
</section>
);
};
Top comments (0)