Skip to content

Instantly share code, notes, and snippets.

@dvdotsenko
Last active July 15, 2019 04:00
Show Gist options
  • Save dvdotsenko/594af8eac0541585d7a077cead663f02 to your computer and use it in GitHub Desktop.
Save dvdotsenko/594af8eac0541585d7a077cead663f02 to your computer and use it in GitHub Desktop.
React + Hooks + Context = easier way to scope TestID tree for elements
import React from 'react'
export function TestIdFactory(separator='-') {
const TestIdContext = React.createContext('')
function TestId({add, set, children}) {
if (!add && !set) {
throw(new Error('Either "set" or "add" prop must be set'))
}
const parentSeed = React.useContext(TestIdContext)
const value = (
set ?
set :
(parentSeed ? parentSeed + separator : '') + add
)
return (
<TestIdContext.Provider value={value}>
{children}
</TestIdContext.Provider>
)
}
// must be named function and must be of form `use[Blah]` for React parser to
// recognize it as function within which we are allowed to run `React.useContext(`
TestId.create = function useTestId(suffix) {
return React.useContext(null, TestIdContext) + (suffix ? separator + suffix : '')
}
return TestId
}
// Example Use:
const TestId = TestIdFactory()
function Child(){
return (
<div>
<h4>{TestId.create()}</h4>
<div>
<label>{TestId.create('label')}
<input type="checkbox"/>
</label>
</div>
<div>
<button>{TestId.create('submit')}</button>
</div>
</div>
)
}
function App(){
return (
<TestId add="main">
<TestId add="A">
<Child/>
</TestId>
<TestId add="B">
<Child/>
</TestId>
<TestId set="newIdTree">
<Child/>
</TestId>
</TestId>
)
}
@dvdotsenko
Copy link
Author

image

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