Skip to content
Author Micah Cambre
RSVPed Attending IndieWebCamp East

IndieWebCamp East 2020 is an online gathering for independent web creators of all kinds, from graphic artists, to designers, UX engineers, coders, hackers, to share ideas, actively work on creating for their own personal websites, and build upon each others creations.

ghost peppers ouch

Lesson learned: ghost peppers affect you the whole way through the body! One accidental ingestion and 12 hours of intermittent heat ???

react’s separation of concerns

It’s funny how patterns and styles get recycled. We’ve seen clothing styles of the 60’s get reintroduced and reused decades later. The TV show Mad Men brought back mid century modern style into the 2000s. And we’ve seen it happen with coding patterns as well.

React Components

One of the first React things I learned is how to create React Components, Capital-C.

export default function NavButton() {
	return(
		<button type="button">Switch Step</button>
	)
}

To use this button, just import it into other files and apply it in the JSX. Straightforward.

Props == HTML Attributes

Buttons usually need to do things, so let’s give this some interactivity.

function NavButton(props) {
	const { transitionCallback, isDisabled } = props

	const handleClick = () => {
		transitionCallback()
	}

	return(
		<button
			onClick={handleClick}
			disabled={isDisabled}
		>
			Switch Step
		</button>
	)
}

2000s me looked at this increasingly used React pattern curiously, because I see onClick={handleClick} attached to the button element. For so many years, often from jQuery or Javascript, I avoided applying event handlers to elements. But here React made that a pattern and my mind goes back in time.

My concerns are separate

I spent the 2000s and into the 2010s learning about, what I eventually started reading from industry folks and books, a computer science term called Separation of Concerns. The idea makes sense on the front-end for many reasons and I became fairly dogmatic about it.

With Separation of Concerns, these three concepts stand on their own:

  • structure (HTML)
  • presentation (CSS)
  • behavior (JS)

By the middle of the 2010s, I wasn’t mixing JS and CSS into HTML, CSS into JS or HTML into JS. We keep them separate, .html, .css, and .js.

By contrast and in practice, however, having worked with WordPress all that time, it was often a losing battle to decouple these languages, quick jQuery or CSS fixes were little inline sprinkles here and there.

<?php
function ratio_calculator() {
    $html = '<style>
	.form-inline .form-group { display:block; margin-bottom: 10px}
</style>
<form id="form" name="form" method="GET" action="#" role="form" class="form-inline">
	<div class="form-group">	
		<label for="RT3" class="t3">RT3</label>
		<input class="form-control" type="text" name="RT3" id="RT3">
	</div>
    <input type="button" class="btn btn-primary" name="button" id="Submit" value="Get Ratio">
</form>
<div id="ratio" style="color:blue;font-weight:bold;font-size:120%"></div>';
return $html;
}
add_shortcode('calculator','calculator_form');

Yuck! I had to grit my teeth and move on.

Then came modern JS frameworks, cemented by React, slowly blowing this concept up. React’s raw JSX syntax requires to cross the decoupling line by adding HTML-like attributes called props containing Javascript and often CSS. A different and controversial method called CSS-in-JS is not only accepted but widely adopted by many React developers. And then there’s the other CSS direction of using utility first libraries like Tailwinds polluting HTML classes, but don’t get me started on that concept!

Separation of Concerns Remixed

In this new paradigm of component-first development, the abstraction for separation of concerns takes on a different look. The separation of concerns is loosely defined within the components themselves. Let’s take a look at what this means.

Here’s my first iteration of the navigation button control component to go from the initial state to the timer state.

function NavButton(props) {
	const { transitionCallback, isDisabled } = props

	const handleClick = () => {
		transitionCallback()
	}

	return(
		<button
			style={{padding:'1rem', backgroundColor:'white'}}
			onClick={handleClick}
			disabled={isDisabled}
		>
			<span className="visuallyhidden">Switch Step</span>
			test
		</button>
	)
}

This code shows a clear mix of all three languages within a Javascript function, with an HTML-like syntax inside of a Javascript return statement, inline CSS in a button element, and an inline onClick event handler calling a function.

Before I started learning how to make websites, the source code of the web documents used similar syntax that kind of looked like the above.

<head>
	<script type="javascript">
		function handleClick() { 
			var transitionCallback = props;
			transitionCallback(); 
		}
	</script>
</head>
<body>
		<input
			align="left"
			clear="left"
			bgcolor="white"
			type="submit"
			onClick="handleClick();"
			disabled="disabled"
			value="test"
		>
</body>

When I first saw React’s syntax, you can imagine how alarmed I was by its seemingly reversion back to the 1990s styling of code. My mental model is so conditioned that this bothered me for a long time, still does to some degree.

Two what end?

As I see modern libraries continue these practices, it appears the pattern of everything inside of JS will continue into the foreseeable future, one way or another. Discussions around native Web Components in the document brings a more dogmatic potential back, but not in its current iteration.

I’m always excited for the future, but I think there will always be a part of me looking of ways to scale back the abstractions and packages needed to build the modern web. Part of that will be my outdated mental model for separation of concerns. Let’s hope browser makers can find better ways to manipulate the DOM and CSSOM without breaking the clients and mixing our concerns!

react reflections in 2020

A few years ago, realizing that both Javascript and React are probably the future of my career in web development, I slowly started reading more and casually learning what I could. I’ve come from such a front-of-the-front-end mindset, bordering on being a developer envying to be a designer, that learning Javscript has taken years for me.

Now that I have both training experience and real-world application of React, I want to jot down various things that I’ve learned as well as still struggle with. (It’ll also be entertaining to re-read this in a while to see how primitive my likes and dislikes are!)

Logical Operators, aka &&

I think this is one of my favorite ways to render components in React. It’s concise and very readable.

const [ activeElement, setActiveElement ] = useState(false);

return (
  <>
    {activeElement && <Accordion onClick={handleClick} />}
  </>
)

Is activeElement true? Sweet, let’s render that Accordion component. Easy to understand, easy to remember.

Form components

One of the more confusing parts of React is Controlled Components vs Uncontrolled Components. Most of the components I’ve written are uncontrolled because of the amount of things I have to do with them. In fact, I find it difficult to justify writing controlled components because doing this misses things for me.

<input
  className="contact-input"
  id="first-name"
  type="text"
  name="first-name"
  defaultValue={first_name}
  onClick={() => setSelectedField("first-name")}
  onKeyDown={e => handleKeyDown(e, "first-name")}
  onChange={e => setData({ ...data, first_name: e.target.value })}
  onKeyUp={validateInput}
/>

See all of these event handlers? Whether it’s validation or another key dependent event, even a custom click handler for custom action, controlled components seem too restricted in what they provide. The biggest drawback for uncontrolled components, unfortunately, is taking the power away from the form’s global handlers like onSubmit. You have to handle this event in the click handler or keydown handler to be able to send or receive the proper data for the element.

Functional Components + Hooks > Class Components

Keeping a mindset of using state in a hook, this allows a few quite appealing benefits.

  • Avoids prop drilling – Whether it’s encapsulating state with useState() or accessing it more globally with useReducer(), state doesn’t have to flow through multiple components to be manipulated as props
  • Less code – It feels and looks better to write functional components with hooks like useState().
  • What lifecycle methods? – I didn’t have to spend a lot of time with a method like ComponentDidMount (among the rest) before I started using useEffect() for most methods to work with data. The more I use it, the more I like its simplicity of helping data flow.

I much prefer updating state with useState() instead of setState(), despite doing similar things. Maybe this is just my personal optics?

Avoiding Prop Drilling

It took me some time to really get the concept of state and props, despite the seemingly simple ways to use them. One of the least favorite things I have to do is find where data starts and how it flows. When you have a microapp that declares a lot of state at top, somehow the the child components need to use a lot of that state and it could pass several levels down before it gets to the correct component for updating as state. Here’s a small example.

function Profile() {
  const [name, setName] = React.useState("")
  
  return <Form name={name} setName={setName} />
}

function Form({name, setName}) {
  const handleChange = e => {
    setName(e.target.value)
    // Do other things here...
  }

  return (
    <div class="form-component">
      <input 
        className="form-input"
        value={name} 
        onChange={() => handleChange(e)}
      />
      <button type="button" onClick={() => setName(name)}>Update
    </div>
  )
}

You get the idea even if this is imperfect. Essentially, we’re giving this form two ways to update: first through the normal onChange method which updates state, which can then be submitted normally, and second using a normal button that sets the name that was already updated by the input field. While this is fairly simple, as an app grows, such as multiple fieldsets of form fields or possibilities of what needs to be stored, updated, created, and so on, props need to be passed down to the various components that are especially written for the form.

If anything, using hooks has made my functions pretty single purposed in what they do to avoid complexity. Maybe it’s more verbose in some ways but it’s ultimately more readable.

Manipulating fetched data

JSON data is still one of my bigger challenges as I learn React and modern Javascript at broad. It can be tedious trying to figure out how to get data from an API to the component in the most efficient way.

Let’s fetch some data.

function PeopleProfiles() {
  const [ profiles, setProfiles ] = useState([])
  const [ activeProfile, setActiveProfile ] = useState(undefined)

  const fetchData = async () => {
    const results = await fetch("https://swapi.co/api/people/1/")
      .then(data => setProfiles(data))
      .catch(err => setErrors(err))
    const activePorfileExists = results.data.some(item => activeProfile === item.name)

    if (!activeProfileExists) setActiveProfile(results.data[0].name)
    setProfiles(results.data)
    return results
  }

  useEffect(() => {
    fetchData()
      .then(results => setActiveProfile(results.data[0].name))
  }, []);
}

Note: this probably won’t work but it’s an okay example for this purpose

Once the data is fetched from the API, we add the data to the profiles state using setProfiles. From there, we can replace, update, create and delete as needed. For visual purposes, there’s an active profile state that will choose the first object if no other profiles are in the active state.

All of this is performed when the component mounts inside of useEffect(). You can see that we’re only calling it once

Because we’re calling the data inside of useEffect() with an empty array as the second argument, this only runs when the component mounts the first time. Any time I tried to add state to the second argument, I kept getting a 429 error where it makes too many calls. I needed to update the state dynamically, which would be equivalent to componentDidUpdate.

I found a better way to update the view with new data is to fetch the data outside of useEffect() and call this function from the component or method that needs the view to update and show the updated data.

Let’s say, within the profile component, I have an input that allows me to update the data. In an ideal scenario, API data fetches are encapsulated into a global file. This app isn’t big enough for that so I’m passing fetchData down to the child component in order to update the view with new data.

  return (
    <>
      <form
        className="Form Form--LovedOnesSpecialDates"
        id="editLovedOne"
      >
        <div className="Form--LovedOnesSpecialDates__wrapper">
          {Profiles.map(profile =>
            <Profiles
              key={profile.id}
              fetchData={fetchData}
            />  
          )}
        </div>
      </form>
    </>
  );

I think this is one of the biggest problem areas with using React. Best practices for fetching and manipulating data have changed a few times as the language has updated itself. I’ve dived deep into React after ES6 was a big part of React via babel and webpack. I also didn’t have to spend a lot of time to understand React’s class component structure. There was just Javascript

But still, there’s a lot of legacy and historical knowledge of plain Javascript that is needed to really help understand the nuances of what React is doing whether it’s mapping through an array or knowing how to pass data from the API to the application’s state.

Conditional loading

Related to logical operators above, React’s conditional loading is not always obvious but interesting nonetheless.

const LovedOne = ({
  id, // number
  activeProfile, // string that's actual a number
  showAddProfile // boolean
}) => {
  return (
    <article
      className={`Profile${parseInt(activeProfile) === id ? " profile-active" : ""}`}
      onKeyDown={!showAddProfile ? handleProfileSwitcher : undefined}
      onClick={!showAddProfile ? handleProfileSwitcher : undefined}
    >
      // Add code here
    </article>
  )
}

It took me too long to find these patterns for render props.

For some reason, I could not pass down a number in the render prop called activeProfile. The console kept complaining so I had to turn the number into a string to get it into this component. So how do I actually use it?

The first attribute is the using a ternary function to set a specific class. The part that wasn’t obvious was matching the id to the activeProfile, which weren’t matching since it’s a string and number. I guess a using loose equality with a == might have solved it, but some linters don’t like it in some situations so I always default to strict equality ===. Either way, I had to turn the string into a number to be able to evaluate if they equal each other.

The second pattern was also a ternary that uses undefined to prevent onKeyDown or onClick from rendering in the markup. This was necessary because at larger viewport widths, these article elements don’t need to be used to help switch the active profile.

The rest

I think I’ll never stop cringing at PascalCase component names both in markup and stylesheets or using className instead of class among other things. I’m still caught in between writing classical components, HTML, CSS and JS vs how React based components. Let’s see what another year of this does!

Good riddance, #chrome. Hello #brave. But #firefox forever. I can’t find a reason to install Chrome on any new computer anymore and have removed it from my existing devices. #privacy

night time, city lights in the background, at night, showing a telephone post with text saying 'big data is watching you'

online resolutions

I never made formal resolutions for any new year. That said, it’s a good practice to better yourself so I think I’ll continue what I started doing last year with my digital presence.

I’m struggling to find a balance between personal privacy and being public. I don’t know where to draw the line right now. For that reason, I’ve practically given up publishing my content or data online. It’s gloomy to feel like the internet wants to do nothing more than take advantage of me. That’s where most of my thoughts go every time I want to post something like this.

So, as a continuation of a personal resolution to take back control of my digital life instead of mindlessly feeding my data into all the apps, I will do two things this year.

Hide

I began a personal quest to protect myself from services like Facebook by encapsulating how I use it everywhere. In a significant way, I’ve removed my voice from most apps and sites by participating as little as possible. I’ve removed any data I can from search engines that I don’t think belongs there. I continue doing these things like not installing Google Chrome on any computer and uninstall it from all my personal computers. Chrome is replaced with Brave Browser but I primarily use Firefox for everything now. I will continue to wind down using large companies products as I’m able to and support freely available open source software.

This all comes at a cost. I don’t have a way to privately share my life outside of some targeted private messages, calls or seeing people in person. It’s extreme and uneasy to disconnect from large parts of society. However, the more I learn about what’s going on, the more I think this active approach to privacy is needed.

Share

I don’t know how I’ll find a good balance, but I must consider that the majority of people I care about live outside of my personal physical and digital bubble. I want to be more present with life outside of occasional private messages. Anything that goes here on this website will be public enough that data aggregators can have it. I can’t control that part but I can control what I put out there.

This is a public pledge that I treat as a fun adventure to learn and help society however possible. I will live as a naive optimist that privacy isn’t completely dead, doesn’t have to be, and there’s always a good way to be online. The internet has provided so much to me, but it’s now a place that takes even more from me. I choose not to give it so much. I will continue this journey by embracing ideals of using small technology.

Inspiration

This is me reminding myself that we’re living in the best of times in human history. Even if my privacy fears are real, I need reminders that ultimately I’ll be fine. Too often, nothing is as bad as it seems in a moment. I can’t change reality but I can change how I react.

20 plus 20

This year, I lived as many years after 2000 as I did before 2000.

Replied to Noteworthy Admin CSS changes in WordPress 5.3 (Make WordPress Core)

WordPress 5.3 will introduce a number of CSS changes in WordPress admin. While the necessity to improve wp-admin accessibility was previously raised in several Trac tickets, Gutenberg’s recent inte…

I admire seeing WordPress move forward keeping accessibility as a priority after its misstep in the 5.0 release. These buttons are a continuation of this priority.

However, it’s disappointing to see a block of form controls and buttons that are too close in design aesthetic to each other.

The image I attached in my previous post is what I see on the comments list page in the Dashboard. I see multiple UI and UX problems with the above block.

I could list out the problematic state changes that are hard to see to the nearly identical styles between input fields and buttons. Inconsistent component heights, confusing applied border colors, Midnight Admin Color Scheme active button state on “Search Comments” button being completely red, and more are things I would attribute to not enough QA and testing for this release.

I think this mini-audit above should give you enough alarm to resolve these issues asap, in the next point releases.

wordpress 5.3 buttons are weird

I updated WordPress to version 5.3, saw the changes to the button styles, and then came upon this.

buttons within WordPress 5.3

I like the updated button styles, which in isolation, are transparent background colors with text and borders that are colored. This style works sometimes and is a good contrast from the button styles with solid background colors.

I don’t like that the hover or focus states of these new button styles barely changes. I also don’t like how closely the buttons mirror the form elements. There’s inconsistency in button styles throughout the whole system now with some that use solid background colors and others using transparent background colors.

I’m disappointed in this from a UX perspective. The overall state of WordPress accessibility might have improved in 5.3 but this feels like a regression.

EDIT: It looks like many others share this opinion, in different ways.
https://make.wordpress.org/core/2019/10/18/noteworthy-admin-css-changes-in-wordpress-5-3/

wifi only

My phone is at home, switched into airplane mode so cellular radio is off, but connected to Wifi with calling enabled. Unnecessary sure, but interesting! Better for security? Probably not. But less is more, right?