Sitemap
Josh Cocciardi

Josh Cocciardi

Dad, Husband, Curious

Utilizing State in React Synthetic Events

5 min readJan 30, 2019

--

My first attempt into the world of React was a bit shaky and reasonably so. I had only been introduced to it 48 hours before determining I would never understand it and should just give up.

Sanity prevailed, after having completed a few labs in my code camp (Flatiron School) and working on this blog post in codeSandbox a bit, React started to come together and finally make some sense.

While working through the this very blog on demonstrating a few different kinds of React Synthetic Events and their attributes I came across the React Docs and found some interesting mouse events — drag related ones. This sent me down a rabbit hole of building a drag and drop example. Currently, there are some changes I would like to make in how it operates but more importantly, it needs to be abstracted into components. I plan to show the app differences on my personal site once I have abstracted each event react component and will link to that here.

To begin with I have a few react SyntheticEvents that are demonstrated using simple event handlers on html elements while others are taking advantage of the component state to leverage dynamic user interactions

The first example utilizes the onClick mouse event, something which will look familiar if you are familiar with vanilla javascript. In the code, the prop which makes the event listener is attached to an <h1> tag:

// the tag in the App render — — — — — -><h1 onClick={this.handleEvent1}>onClick</h1>
// instance method — — — — — ->
handleEvent1 = event => {
console.log(“event1”);
}; //end event1

The event is triggered on the h1 target set inline, this.method points to an instance method wrapped in the App class which logs a string letting use know we have triggered an event.

Next, something a little more fun…The second event is attached to an input with type attribute of text. This is how it is initially rendered, however it is not hardcoded this way. This is done by storing the type information as a string in the state (state.type = “text”). By initializing our app this way the input renders as a text input with placeholder value of onFocus/onBlur. In addition to the state declaration, we need two additional helpers in the App class to handle the onFocus and onBlur synthetic events. Here is the code…

state = {
type: “text”,
//don't worry about these three state keys yet.... classone: “draggable dragfrom”,
classfloat: “”,
classtwo: “draggable dragto”
};
onFocus = () => {
this.setState({
type: “file”
});
};
onBlur = () => {
this.setState({
type: “range”
});
};
///and here is how it is attached to the input element
<input
type={this.state.type}
onFocus={this.onFocus}
onBlur={this.onBlur}
placeholder="onFocus and onBlur"
/>

From the above code you may be able to tell what is happening. The input type is set to {this.state.type} which will be re-rendered anytime the state changes. The input carries two props, onBlur={this.onBlur} and onFocus={this.onFocus} both call on an instance method in App class to handle the event. Moving up to the instance methods we can see what the events are actually trigger, a state change! Each method changes the state.type to something user-defined, in this case I chose range and file input type attributes to showcase some different input types. The state is changed and the input re-renders, that’s it! thanks React!

Get Josh Cocciardi’s stories in your inbox

Join Medium for free to get updates from this writer.

The third example is a pretty straightforward synthetic event, similar to the first click example but it is demonstrating something called onContextMenu. This may or may not be something you are familiar with but very simply it triggers on a right click. Here I am pointing to an instance method which logs that right click was used and also adds the event.preventDefault() preventing the context menu (right click box) from popping up, cool!

Next up is the onKeyPress. A text input is rendered with a listener attached. The instance method that is called onKeyPress has access to the synthetic event which has an attribute of key allowing us to snag the string associated with the key that is pressed.

Finally, the one the one that sent me down the rabbit hole, onDrag … I saw this event in the list on the React Docs and began looking up how to use it which quickly led to me finding the ability to attribute ‘draggability’ to any html element! draggable="true" it’s that easy. So I thought hey if dragging is this easy, what about drag and drop?

Conceptually, I don’t think it is too advanced, but testing each piece of the puzzle and the logic took some time to reason out in practice. Before I shared the state had a few more key value pairs besides the type: ‘text’. Similar to how the input field was changed from a text input to a file upload and then to a range onBlur, the drag and drop is using state to manipulate the a few elements but it is done across a few different event handlers and with some CSS. Initially, the page is rendered with two <div>’s with a border box and one holding a single smaller div that is centered. These divs were given border-radius of 50% of their size to make them appear as circles, mostly just for fun. Anyway, there are 4 main handlers to review.

//props for dropzone
onDragOver={this.dragOver}
onDragEnter={this.dragEnter}
onDrop={this.dragDrop}
onDragLeave={this.dragLeave}
//props for dragging object
className={this.state.classone}
draggable="true"
onDragStart={this.dragStart}
onDragEnd={this.dragEnd}
dragOver = event => {
event.preventDefault();
}; //end of dragEnd
dragEnd = event => {
event.target.style.opacity = 1;
}; //end of dragEnd
dragStart = event => {
event.target.style.opacity = 0.3;
if (event.target.id === "one") {
if (event.target.className === "draggable dragfrom") {
this.setState({ classfloat: "draggable dragto" });
} else if (event.target.className === "draggable dragto")
this.setState({ classfloat: "draggable dragfrom" });
} else if (event.target.id === "two") {
if (event.target.className === "draggable dragfrom") {
this.setState({ classfloat: "draggable dragto" });
} else if (event.target.className === "draggable dragto")
this.setState({ classfloat: "draggable dragfrom" });
}//end else if two
}; //end of dragstart
dragDrop = event => {
event.preventDefault();
if (event.target.id === "outerone") {
this.setState({ classone: this.state.classtwo }, () => {
this.setState({ classtwo: this.state.classfloat });
});
} else if (event.target.id === "outertwo") {
this.setState({ classtwo: this.state.classone }, () => {
this.setState({ classone: this.state.classfloat });
});
}//end else if
}; //end of dragDrop

Okay, now let’s look at it in action! Try opening the codesandbox console to view the event output.

Resources I found handy...--react docs synthetic events https://reactjs.org/docs/events.html
--focus/blur help https://codepen.io/comakai/pen/WvzRKp?
editors=0010html input attributes -https://www.w3schools.com/tags/att_input_type.asp
--drag and drop inspiration https://medium.com/the-andela-way/react-drag-and-drop-7411d14894b9
--MDN resource on dragstart https://developer.mozilla.org/en-US/docs/Web/Events/dragstart

--

--