React Props and Event Handling
Learn to pass and handle React props, customize components, and use event handlers in TypeScript.
We'll cover the following...
React props
When we create a React component, we are able to give it properties that are handed down from the parent component to the child component. These properties can
include both display properties and event handlers. As an example of this, let’s put a button on the screen and see how to both handle the onClick
DOM event within the component itself and how to trigger an event on the parent component.
We will start by creating a new React component in a file named MyButton.tsx
:
import React from "react";export class MyButton extends React.Component {render() {return (<Button color="primary">Click me</Button>)}}
Here, we create a new React component named MyButton
that extends React.Component
and has a single render
function. Within the render
function, we add a React Material-UI component named Button
, which will render a button to the screen with the text “Click me.” Note that we have also exported the MyButton
class so that we can import it in the App.tsx
file as follows:
import React from 'react'; import './App.css'; import { MyButton } from './MyButton'; class App extends React.Component { render() { return ( <MyButton/> ) } } export default App;
Here, we import the MyButton
component from the MyButton.tsx
file on line 3 and then use it in the render
function on line 8.
Running the application now renders a button. We can see that the App
component is rendering the MyButton
component, which in turn is rendering a Material-UI Button component.
In order to customize our MyButton
component, we will need to define a set of properties, or props, that are available to set via the parent component. This is accomplished by ...