Skip to content

Instantly share code, notes, and snippets.

@jhonsore
Last active January 28, 2022 16:29
Show Gist options
  • Save jhonsore/e439bcf1eafe5220193a337a49bca699 to your computer and use it in GitHub Desktop.
Save jhonsore/e439bcf1eafe5220193a337a49bca699 to your computer and use it in GitHub Desktop.
React tips
//found at: https://fettblog.eu/typescript-react/events/
import React, { Component, MouseEvent } from 'react';
export class Button extends Component {
/*
Here we restrict all handleClicks to be exclusively on
HTMLButton Elements
*/
handleClick(event: MouseEvent<HTMLButtonElement>) {
event.preventDefault();
event.preventDefault();
const button: HTMLButtonElement = event.currentTarget;
}
/*
Generics support union types. This event handler works on
HTMLButtonElement and HTMLAnchorElement (links).
*/
handleAnotherClick(event: MouseEvent<HTMLButtonElement | HTMLAnchorElement>) {
event.preventDefault();
alert('Yeah!');
}
render() {
return <button onClick={this.handleClick}>
{this.props.children}
</button>
}
}
// the interface needs to explicitly declare which strings are safe to pass
interface HeadingProps extends React.HTMLAttributes<HTMLHeadingElement> {
headingLevel: "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "p"
}
const TsHeading = ({
headingLevel = "p",
children,
className,
}: HeadingProps) => {
const Heading = ({ ...props }: React.HTMLAttributes<HTMLHeadingElement>) =>
React.createElement(headingLevel, props, children)
return <Heading className={className}>{children}</Heading>
}
const Banner: React.FC<{ headingText: string; description: string }> = ({
headingText,
description,
}) => (
<div>
<TsHeading headingLevel="h2">{headingText}</TsHeading>
<p>{description}</p>
</div>
)
import { ChangeEvent } from 'react';
import React = require('react');
interface Props extends React.InputHTMLAttributes<HTMLInputElement> {
name?: string;
label?: string;
}
export const Input: React.FC<Props> = ({ ...args }) => {
const handleInput = (event: ChangeEvent<HTMLInputElement>) => {
event.preventDefault();
console.log(event.target.value);
};
return (
<div>
<input type="text" {...args} onChange={handleInput} />
</div>
);
};
import { ChangeEvent } from 'react';
import React = require('react');
interface Props extends React.SelectHTMLAttributes<HTMLSelectElement> {}
export const Select: React.FC<Props> = ({ ...args }) => {
const selectChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
event.preventDefault();
console.log(event.target.value);
};
return (
<div>
<select onChange={selectChange} {...args}>
<option selected disabled>
Choose one
</option>
<option value="blue">Blue</option>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="yellow">Yellow</option>
<option value="kindacode.com">Kindacode.com</option>
</select>
</div>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment