Introduction
So just like react provides an abstraction layer to the DOM elements it also provides abstraction layer around the events and it is called as synthetic events,
- onClick basically allowed us to pass a function that will get executed once the button is clicked
- everything that is inside the curly braces is javasript and everything that is outside that is markup language.
Why there is an Abstraction around events?
-since this will provide better performance and the same functionality in all browsers.
Example
- Create a button and onClick of that button call a method that will print something to console.
const first = () => {
const displayHelloWorld = (e) => {
//here e.preventDefault() --> will basically prevents the default behavior like submitting the form
e.preventDefault()
console.log('hello world')
}
<button onClick={displayHelloWorld}>Click to Save</button>
here we have use the e.preventDefault() to prevent the default behavior of the button that is to submit the form.
Create button that will print the value and call the function using onClick and call back.
import React from 'react'
const saveButtonValue = (e) => {
e.preventDefault()
console.log(e.target.value)
}
const displayInputVaue = (e) => {
console.log(e.target.value)
}
return (
<div>
<button value='buttonInitialValue' onClick={(e) => saveButtonValue(e)}>
Save Value{' '}
</button>
</div>
)
}
export default first
- Third example is of onChange , onChange will be used with input where once there is a change we will print the value in the console.
import React from 'react'
const displayInputVaue = (e) => {
console.log(e.target.value)
}
return (
<div>
<input onChange={(e) => displayInputVaue(e)} />
</div>
)
}
export default first
- this will print the value as soon as there is some change in the input box
Complete component with all the three cases
import React from 'react'
const first = () => {
const displayHelloWorld = (e) => {
e.preventDefault()
console.log('hello world')
}
const saveButtonValue = (e) => {
e.preventDefault()
console.log(e.target.value)
}
const displayInputVaue = (e) => {
console.log(e.target.value)
}
return (
<div>
<h1>Here we are learning</h1>
*/}
<button onClick={displayHelloWorld}>Click to Save</button>
<button onClick={(e) => displayHelloWorld(e)}>Using call back</button>
<button value='buttonInitialValue' onClick={(e) => saveButtonValue(e)}>
Save Value{' '}
</button>
<input onChange={(e) => displayInputVaue(e)} />
</div>
)
}
export default first