Last active
January 26, 2023 07:56
-
-
Save queerviolet/5eb2d724a7cc86289b25e2296d748da9 to your computer and use it in GitHub Desktop.
Component injection in React
This file contains hidden or 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
const React = require('react') | |
const List = ({ | |
items, | |
Item = Todo.Item // Components recieve any components they depend on via props. | |
// The default assignment keeps our public interface clean. | |
}) => <ul>{items.map((item, index) => <Item key={index}>{item}</Item>)}</ul> | |
const Item = ({ | |
index, | |
children, | |
}) => <li> | |
<input type='checkbox' name='done'/> | |
{children} | |
</li> | |
const Todo = {List, Item} | |
console.log(require('react-dom/server') | |
.renderToString( | |
<List items={['hello', 'world']}/> // We don't have to specify an injection | |
// to use the component. | |
)) | |
/* | |
Output: | |
<ul data-reactroot="" data-reactid="1" data-react-checksum="306405087"><li data-reactid="2"><input type="checkbox" name="done" data-reactid="3"/><!-- react-text: 4 -->hello<!-- /react-text --></li><li data-reactid="5"><input type="checkbox" name="done" data-reactid="6"/><!-- react-text: 7 -->world<!-- /react-text --></li></ul> | |
*/ | |
/**** Testing *****/ | |
const chai = require('chai'), {expect} = chai | |
chai.use(require('chai-shallow-deep-equal')) | |
typeof describe !== 'undefined' && | |
describe('Todo.List', () => { | |
it('returns a list of items', () => | |
expect(Todo.List({ | |
items: ['get milk', 'destroy patriarchy'], | |
Item: 'todo-item' // When testing, we inject a string. | |
// JSX will turn this into a simple tag. | |
})).to.shallowDeepEqual( | |
// Comparison is now a simple tree comparison | |
<ul> | |
<todo-item key={0}>get milk</todo-item> | |
<todo-item key={1}>destroy patriarchy</todo-item> | |
</ul>)) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment