News from Verona ( ReactJS Day – October, 5th, 2018)

I wrote some kind of report about ReacJS day – Verona, October, 5th. But my pc blocked (TODO: buy a new pc, once I understand which), I did not saved the document. I taked a screenshot.

My experiment on React.context will focus on edit state of a page. Currently the page is made of various components and some are switchable to edit-mode and view-mode. I want to add constraint that only one element in a page is on edit mode, and also to add the behavior of switch-to-view-mode-on-ESC-key.

I should provide a value via EditState.provider : elementid

For this I need that every editable element have a unique id in the page.

Some faced it in https://github.com/facebook/react/issues/1137, the most immediate and simple proposed solution is
https://github.com/facebook/react/issues/1137#issuecomment-95699269

But I will skip this problem passing a register function

const EditStateContext = React.createContext( {
   editElement: null,
   register: () => {}, // return an unique id
   editModeOn: (id) => {}, // toggle on
   editModeOff: (id) => {} // toggle off
})

as documented the value should be the state of a containing component

import { EditStateContext } from './EditStateContext';
class App extends React.Component {
  constructor(props) {
    super(props);
    this.editableComponents = [];
    this.register = () => {
	let newLength = this.editableComponents.push(this.editableComponents.length);
	return newLength - 1; // this is enough to stay safe on race condition
    }
    this.editModeOn = (id) => {this.setState({editElement:id})}
    this.editModeOff = (id) => {this.setState((oldState) => { if (oldState.editElement ===id) {return {editElement:id} }} )}
    this.state = {
	// about js lang I dislike the use of -1 for notFound of indexOf, but ...
	editElement: -1,
	register: this.register,
	editModeOn: this.editModeOn,
	editModeOff: this.editModeOff
    }
  }
  componentDidMount() {
	document.addEventListener('onkeyup',(e) => {
		if (e.code === 'ESC') { // Replace with something meaninful
			this.setState(state=>{ return {editElement: -1 }} ));
		}
	});
  }
  render() {
	return (
		<EditStateContext.Provider value={this.state}>
		  <Content />
		</EditStateContext.Provider>
	);
  }
}

The consumer will receive the value

import { EditStateContext } from './EditStateContext';

function withSkipEditableEl(Element) {
   return (
	<EditStateContext.Consumer>
		{ (props) => (<Element ...props />) }
	</EditStateContext.Consumer>
   )
}

Now I can use that HOC function passing the editable element.

It may works, I will test tomorrow.

I am still confused about contexxt and a number of pending tasks on the go.


Posted

in

,

by

Tags: