Skip to content

Instantly share code, notes, and snippets.

const areEqual = (prevProps, nextProps) => (
prevProps.myProp === nextProps.myProp
);
const Hello = ({ myProp }) => (
<div>{myProp}</div>
);
export default React.memo(Hello, areEqual);
const Hello = () => {
const inputRef = useRef(null);
return (
<input ref={inputRef} type='text' />
<button onClick={() => inputRef.current.focus()}>click to focus the input</button>
);
}
// Hook reducer
const reducer = (state, action) => {
switch(action.type) {
case 'initial data':
return action.payload;
}
}
// Hook actions
const fetchData = async () => {
const Hello = () => {
const [isOpen, toggleIsOpen] = React.useState(false);
return (
<div>
<button onClick={(prevValue) => toggleIsOpen(!prevValue)}>click me</button>
{isOpen ? <p>I'm open!</p> : <p>I'm closed!</p>}
</div>
);
};
const Hello = () => {
const [inputValue, setInputValue] = React.useState('');
return (
<input
onChange={(e) => setInputValue(e.target.value)}
value={inputValue}
/>
)
}
const Hello = () => {
const [number, updateNumber] = React.useState(0);
return (
<div>
<p>{number}</p>
<button onClick={(prevNum) => updateNumber(prevNum + 1)}>Add 1</button>
<button onClick={(prevNum) => updateNumber(prevNum - 1)}>Remove 1</button>
</div>
)
}
class Modal extends Component {
private modalRef = createRef;
closeModal = (e) => {
const { modalProps } = this.props;
const node = this.modalRef.current;
// ignore if click is inside the modal
if (node && node.contains(e.target)) {
return;
}
const Header = () => (
<StyledHeader>
<nav>
<ModalContext.Consumer>
{(modalProps) => (
<Button onClick={modalProps.showModal}>login</Button>
{/*
we pass modalProps so the Modal can use them to render if show is true
and to provide the hideModal method for our close functionality
*/}
import React, { Component, createContext } from "react";
const ModalContext = createContext({
hideModal: () => null,
show: false,
showModal: () => null
});
export default ModalContext;
@Kornil
Kornil / modal.jsx
Last active December 30, 2018 11:29
class Modal extends Component {
modalRef = createRef();
state = {
show: false
}
closeModal = (e) => {
const node = this.modalRef.current;
if (node && node.contains(e.target)) {