Last active
July 15, 2019 04:00
-
-
Save dvdotsenko/594af8eac0541585d7a077cead663f02 to your computer and use it in GitHub Desktop.
React + Hooks + Context = easier way to scope TestID tree for elements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | |
) | |
} |
Author
dvdotsenko
commented
Jul 14, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment