Skip to content

Instantly share code, notes, and snippets.

@SirSerje
Last active February 21, 2020 06:56
Show Gist options
  • Save SirSerje/239ddebd33c9352a682e1d01ec9cce59 to your computer and use it in GitHub Desktop.
Save SirSerje/239ddebd33c9352a682e1d01ec9cce59 to your computer and use it in GitHub Desktop.
react how to refs
import React from 'react';
import './App.css';
import './index.css'
function App() {
return (
<div className="App">
<Parent/>
</div>
);
}
class Parent extends React.PureComponent {
constructor(props) {
super(props);
this.state = {};
this.handleButtonRef = React.createRef();
}
handleDickKnowWhat = () => {
this.handleButtonRef.current.handleClick()
};
render() {
return (
<>
<h1>Parent</h1>
<div className="myblock">
<Child1 ref={this.handleButtonRef}/>
<Child2 handler={this.handleDickKnowWhat}/>
</div>
</>
)
}
}
class Child1 extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
title: 'some',
isActive: false,
}
}
handleClick = (e) => this.setState(({ isActive }) => ({ isActive: !isActive }));
render() {
return (
<div style={{border: '1px solid purple'}}>
<h2>First Child</h2>
{this.state.isActive && (<h3>{this.state.title}</h3>)}
<button onClick={this.handleClick}>
child button
</button>
</div>
)
}
}
class Child2 extends React.PureComponent {
render() {
const { handler } = this.props;
return (
<div style={{border: '1px solid violet'}}>
<h2>Second Child</h2>
<button onClick={handler}>toggle child 1</button>
</div>
)
}
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment