Skip to content

Instantly share code, notes, and snippets.

@dandelionadia
Created April 8, 2020 09:26
Show Gist options
  • Save dandelionadia/22801d4bc78612afeee80046a826f20c to your computer and use it in GitHub Desktop.
Save dandelionadia/22801d4bc78612afeee80046a826f20c to your computer and use it in GitHub Desktop.
Using Refs
class Person extends Component {
constructor(props) {
super(props);
this.inputElementRef = React.creatRef();
}
componentDidMount() {
this.inputElementRef.current.focus();
}
render() {
return (
<input ref={this.inputElementRef} type="text"/>
)
}
}
export const Cockpit: React.FC<CockpitProps> = React.memo(props => {
const toggleBtnRef = useRef<HTMLButtonElement>(null);
useEffect(() => {
const { current } = toggleBtnRef;
if (!current) {
return;
}
current.click();
}, []);
return (
<>
<h1>React App</h1>
<button ref={toggleBtnRef} onClick={props.onClick}>
Switch Name
</button>
</>
);
});
export const Cockpit: React.FC<CockpitProps> = React.memo(props => {
const toggleBtnRef = useRef<HTMLButtonElement>(null);
useEffect(() => {
toggleBtnRef.current?.click()
}, []);
return (
<>
<button ref={toggleBtnRef} onClick={props.onClick}>
Switch Name
</button>
</>
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment