Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@Rendalf
Last active March 19, 2018 08:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Rendalf/ef14f2202f95cb5e1a3cbaf138a24523 to your computer and use it in GitHub Desktop.
Save Rendalf/ef14f2202f95cb5e1a3cbaf138a24523 to your computer and use it in GitHub Desktop.
Preact fails ref
// failed ref
const MyShinyComponent = ({ isFooShown }) => (
<div className='wrapper'>
{ isFooShown && (
<div className='foo'>Foo</div>
)}
<div
className='bar'
ref={ someRefFunc }
>
Bar
</div>
</div>
)
// fix with empty element
const MyShinyComponent = ({ isFooShown }) => (
<div className='wrapper'>
{ isFooShown
? <div className='foo'>Foo</div>
// returning empty div doesn't cause calling ref with `null`
: <div />
}
<div
className='bar'
ref={ someRefFunc }
>
Bar
</div>
</div>
)
// fix with key (best solution)
const MyShinyComponent = ({ isFooShown }) => (
<div className='wrapper'>
{ isFooShown && (
<div className='foo'>Foo</div>
)}
<div
className='bar'
ref={ someRefFunc }
key='bar'
>
Bar
</div>
</div>
)
@Rendalf
Copy link
Author

Rendalf commented Mar 16, 2018

Preact calls ref with null after isFooShown changes from true to false and doesn't call ref after that.

@Rendalf
Copy link
Author

Rendalf commented Mar 16, 2018

There is dedicated issue: preactjs/preact#753

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment