Children.. ??

Children are very important and at the same time troublemakers,
just as in real life would my parenting friends say ?.
React created a seperate class to handle them: ReactMultiChildren.
But we don’t need that in our lifes yet. We’re just practicing :smile:

We know that our children live in this.props.children.
Soooo, in our updateVElement function we can identify them.
Now we just need to implement the logic to handle those troublemakers:

  1. index.js
  2. ...
  3. function updateVElement(prevElement, nextElement) {
  4. const dom = prevElement.dom;
  5. nextElement.dom = dom;
  6. if (nextElement.props.children) {
  7. updateChildren(prevElement.props.children, nextElement.props.children, dom);
  8. }
  9. if (prevElement.style !== nextElement.style) {
  10. Object.keys(nextElement.style).forEach((s) => dom.style[s] = nextElement.style[s])
  11. }
  12. }
  13. function updateChildren(prevChildren, nextChildren, parentDOMNode) {
  14. if (!Array.isArray(nextChildren)) {
  15. nextChildren = [nextChildren];
  16. }
  17. if (!Array.isArray(prevChildren)) {
  18. prevChildren = [prevChildren];
  19. }
  20. for (let i = 0; i < nextChildren.length; i++) {
  21. //We're skipping a lot of cases here. Like what if
  22. //the children array have different lenghts? Then we
  23. //should replace smartly etc. :)
  24. const nextChild = nextChildren[i];
  25. const prevChild = prevChildren[i];
  26. //Check if the vNode is a vText
  27. if (typeof nextChild === 'string' && typeof prevChild === 'string') {
  28. //We're taking a shortcut here. It would cleaner to
  29. //let the `update` function handle it, but we would to add some extra
  30. //logic because we don't have a `tag` property.
  31. updateVText(prevChild, nextChild, parentDOMNode);
  32. continue;
  33. } else {
  34. update(prevChild, nextChild);
  35. }
  36. }
  37. }

We have an updateChildren function that is called when the current vElement has children.
The updateChildren is very naivly implemented. For example it doesn’t take into account
the possibility that vNode can be added or removed (the arrays would have different lenghts).
But we won’t worry about that.

We also take a quick shortcut to check if we’re dealing with a vText.
If it’s a vText, we directly call the updateVText function. Of course it
would be nicer to call the update function directly to handle the different types,
but that would request some refactoring, we aint got no time for that.

The only thing remaining to be implemented is the updateVText function:

  1. index.js
  2. ...
  3. function updateVText(prevText, nextText, parentDOM) {
  4. if (prevText !== nextText) {
  5. parentDOM.firstChild.nodeValue = nextText;
  6. }
  7. }

Easy does it! Let’s build a proper application now:

  1. class NestedApp extends Component {
  2. constructor(props) {
  3. super(props);
  4. }
  5. render() {
  6. return createElement('h1', { style: { color: '#'+Math.floor(Math.random()*16777215).toString(16) } }, `The count from parent is: ${this.props.counter}`)
  7. }
  8. }
  9. class App extends Component {
  10. constructor() {
  11. super();
  12. this.state = {
  13. counter: 1
  14. }
  15. setInterval(() => {
  16. this.setState({ counter: this.state.counter + 1 })
  17. }, 500);
  18. }
  19. render() {
  20. const { counter } = this.state;
  21. //background color stolen from: https://www.paulirish.com/2009/random-hex-color-code-snippets/
  22. return createElement('div', { style: { height: `${10 * counter}px`, background: '#'+Math.floor(Math.random()*16777215).toString(16) } }, [
  23. `the counter is ${counter}`,
  24. createElement('h1', { style: { color: '#'+Math.floor(Math.random()*16777215).toString(16) } }, `${'BOOM! '.repeat(counter)}`),
  25. createElement(NestedApp, { counter: counter})
  26. ]);
  27. }
  28. }

OOPS this doesn’t seem to work. The error is: children.forEach is not a function.
The dangers of iteration!

The problem is that in our mountVElement function, props.children can be an array, but
can also be a plain string. It is an easy fix. In our if statement we make sure
that we’re using an array.

  1. if (props.children) {
  2. if (!Array.isArray(props.children)) {
  3. mount(props.children, domNode)
  4. } else {
  5. props.children.forEach(child => mount(child, domNode));
  6. }
  7. }

Let’s try again!

OOH YEAHHHH ITS TIME TO PREMATURELY CELEBRATE YOO.

Updating children - 图2

We’ve almost made it. Everythang seems to work nicely. We can pass Components as children to otherComponents
which is awesome! It also renders the passed props. However, if the props are updated this is not represented in the UI.

If you look closely you will see that the render function of the NestedApp isn’t called after the initial render.
We need to fix that!

Updating the mighty Components!

As we’ve found out when we were writing the code for mounting Components, Components are behaving differently then our vElements and vTexts.
That is a good thing because it creates all kinds of opportunities, but it does mean we have to think a little bit harder about the implementation
of…. the updateVComponent function.

What do we actually want? Mentally, I like to split Components in two, 1) the render() function and 2) everything else.

The eventual goal is to call the update function, with an prevRenderedElement and nextRenderedElement. The render function
will give us the nextRenderedElement. The prevElement we can grab from this._currentElement, as we’ve already discussed.

However, before we’re calling render() we can do some housekeeping. We swap the _instance, dom and props from our
previous to our next vComponent, and update the _instance property and its _currentElement property with the nextRenderedElement.

Then we call render(), and call update with the prevRenderedElementand nextRenderedElement and let recursion
do it’s magic ?

  1. index.js
  2. ...
  3. function updateVComponent(prevComponent, nextComponent) {
  4. //get the instance. This is Component. It also
  5. //holds the props and _currentElement;
  6. const { _instance } = prevComponent;
  7. const { _currentElement } = _instance;
  8. //get the new and old props!
  9. const prevProps = prevComponent.props;
  10. const nextProps = nextComponent.props;
  11. //Time for the big swap!
  12. nextComponent.dom = prevComponent.dom;
  13. nextComponent._instance = _instance;
  14. nextComponent._instance.props = nextProps;
  15. const prevRenderedElement = _currentElement;
  16. const nextRenderedElement = _instance.render();
  17. //finaly save the nextRenderedElement for the next iteration!
  18. nextComponent._instance._currentElement = nextRenderedElement;
  19. //call update
  20. update(prevRenderedElement, nextRenderedElement, _instance._parentNode);
  21. }

Tell me about it, this can be massively confusing :smile: I would suggest to put some debugger statements
between the different lines and see what is doing what. You will figure it out!

Remember, we’re doing a lot preparing for the next iteration and next and next and next… Recursion is very
important
!

? If we would refactor our updateComponent function on our Component class, we could
reuse logic here.

We just need to adjust one small thing. We need to adjust our update function so that it can call the
updateVComponent function when needed.

  1. index.js
  2. ...
  3. function update(prevElement, nextElement) {
  4. //Implement the first assumption!
  5. if (prevElement.tag === nextElement.tag) {
  6. //Inspect the type. If the `tag` is a string
  7. //we have a `vElement`. (we should actually
  8. //made some helper functions for this ;))
  9. if (typeof prevElement.tag === 'string') {
  10. updateVElement(prevElement, nextElement);
  11. } else if (typeof prevElement.tag === 'function') {
  12. updateVComponent(prevElement, nextElement);
  13. }
  14. } else {
  15. //Oh oh two elements of different types. We don't want to
  16. //look further in the tree! We need to replace it!
  17. }
  18. }

Time to take our new code for a testdrive. Let’s redefine our new application:

Please work ???

  1. class NestedApp extends Component {
  2. constructor(props) {
  3. super(props);
  4. }
  5. render() {
  6. return createElement('h1', { style: { color: '#'+Math.floor(Math.random()*16777215).toString(16) } }, [
  7. `The count from parent is: ${this.props.counter}`,
  8. createElement('div', {}, `Some text ${this.props.counter}`)
  9. ])
  10. }
  11. }
  12. class App extends Component {
  13. constructor() {
  14. super();
  15. this.state = {
  16. counter: 1
  17. }
  18. setInterval(() => {
  19. this.setState({ counter: this.state.counter + 1 })
  20. }, 100);
  21. }
  22. render() {
  23. const { counter } = this.state;
  24. //background color stolen from: https://www.paulirish.com/2009/random-hex-color-code-snippets/
  25. return createElement('div', { style: { height: `${10 * counter}px`, background: '#'+Math.floor(Math.random()*16777215).toString(16) } }, [
  26. `the counter is ${counter}`,
  27. createElement('h1', { style: { color: '#'+Math.floor(Math.random()*16777215).toString(16) } }, `${'BOOM! '.repeat(counter)}`),
  28. createElement(NestedApp, { counter: counter})
  29. ]);
  30. }
  31. }
  32. const root = document.body;
  33. mount(createElement(App), root);

AWESOME! ✋?✋?✋? (high fives) The app is rerendering, props are updated, we can nest components. We should be proud!

ShouldComponentUpdate?

We haven’t really discussed lifecycle methods yet. But at this stage it would be nice to add the shouldComponentUpdate
lifecycle method.

We need to update our Component class a bit, so that it will return true as default:

  1. Class Component {
  2. ...
  3. //add this in existing code
  4. shouldComponentUpdate() {
  5. return true;
  6. }
  7. }

Now we can update our updateVComponent function:

  1. function updateVComponent(prevComponent, nextComponent) {
  2. ...
  3. if (_instance.shouldComponentUpdate()) {
  4. const prevRenderedElement = _currentElement;
  5. const nextRenderedElement = _instance.render();
  6. //finaly save the nextRenderedElement for the next iteration!
  7. nextComponent._instance._currentElement = nextRenderedElement;
  8. //call update
  9. update(prevRenderedElement, nextRenderedElement, _instance._parentNode);
  10. }
  11. //do nothing!
  12. }

As you can see, we call the shouldComponentUpdate() function before we want to start rendering. If
the function returns false, we do nothing and don’t rerender. Let give it a try:

  1. index.js
  2. class NestedApp extends Component {
  3. constructor(props) {
  4. super(props);
  5. }
  6. shouldComponentUpdate() {
  7. return this.props.counter % 2;
  8. }
  9. render() {
  10. console.log('OK IM RERENDERING!');
  11. return createElement('h1', { style: { color: '#'+Math.floor(Math.random()*16777215).toString(16) } }, [
  12. `The count from parent is: ${this.props.counter}`,
  13. createElement('div', {}, `Some text ${this.props.counter}`)
  14. ])
  15. }
  16. }

ANDDDDD there you go! Now we can build all efficient apps and shit! ??

If the code is not working, or If I accidently skipped parts, please let me know. The
code we should have at this point. can be found here

I really hope you now have a better conceptual understanding how React
and React-like libraries could work. I’ve tried to really seperate
all the different moving parts, so that the different concepts are hopefully
easier to grasp.

We could even create a directory structure like:

  1. vComponent
  2. - mount.js
  3. - update.js
  4. - create.js
  5. vElement
  6. - mount.js
  7. - update.js
  8. - create.js
  9. vText
  10. - mount.js
  11. - update.js
  12. - create.js
  13. Component.js
  14. creating.js
  15. mounting.js
  16. updating.js

Next we will be diving into React.js, The seperation in the code is less clear.
Most responsbilities are put on the different Components. Making it harder
to understand what is going one. Hopefully this can work as a reference.

One ?