Browse Source

Updated forward-refs example to use class component

main
Brian Vaughn 7 years ago
parent
commit
b25276a80e
  1. 6
      content/docs/context.md
  2. 11
      examples/context/forwarding-refs-app.js
  3. 16
      examples/context/forwarding-refs-fancy-button.js
  4. 12
      examples/context/forwarding-refs.js
  5. 2
      examples/context/multiple-contexts.js

6
content/docs/context.md

@ -99,7 +99,11 @@ A more complex example with dynamic values for the theme:
## Forwarding Refs to Context Consumers
`embed:context/forwarding-refs.js`
**fancy-button.js**
`embed:context/forwarding-refs-fancy-button.js`
**app.js**
`embed:context/forwarding-refs-app.js`
## Legacy API

11
examples/context/forwarding-refs-app.js

@ -0,0 +1,11 @@
import FancyButton from './fancy-button';
const ref = React.createRef();
// Our ref will point to the FancyButton component,
// And not the ThemeContext.Consumer that wraps it.
// This means we can call FancyButton methods like ref.current.focus()
// highlight-next-line
<FancyButton ref={ref} onClick={handleClick}>
Click me!
</FancyButton>;

16
examples/context/forwarding-refs-fancy-button.js

@ -0,0 +1,16 @@
class FancyButton extends React.Component {
focus() {
// ...
}
// ...
}
// Use context to pass the current "theme" to FancyButton.
// Use forwardRef to pass refs to FancyButton as well.
// highlight-range{1,3}
export default React.forwardRef((props, ref) => (
<ThemeContext.Consumer>
{theme => <Button {...props} theme={theme} ref={ref} />}
</ThemeContext.Consumer>
));

12
examples/context/forwarding-refs.js

@ -1,12 +0,0 @@
const Button = ({theme, children}) => (
<button className={theme ? 'dark' : 'light'}>
{children}
</button>
);
// highlight-range{1,3}
export default React.forwardRef((props, ref) => (
<ThemeContext.Consumer>
{theme => <Button {...props} theme={theme} ref={ref} />}
</ThemeContext.Consumer>
));

2
examples/context/multiple-contexts.js

@ -8,7 +8,7 @@ const UserContext = React.createContext();
// An intermediate component that depends on both contexts
const Toolbar = props => {
// highlight-range{2-10}
// highlight-range{2-10}
return (
<ThemeContext.Consumer>
{theme => (

Loading…
Cancel
Save