Conditional Rendering in React

Conditionally rendering content is a pretty common pattern in React components.

class MyComponent extends Component {
  render() {
    const { user } = this.props;
    return (
      <div>
        {user && <h1>{user.name}</h1>}
        {/* other content */}
      </div>
    );
  }
}

This can quickly get messy when you introduce multiple parmeters or large conditional content blocks

render() {
  const { user, profile, otherData } = this.props;
  const shouldDisplayProfile = user && profile && otherData;
  return (
    <div>
      {shouldDisplayProfile &&
        <div>





        </div>
      }
      {/* other content */}
    </div>
  );
}

And don’t even mention ternary operators. Nothing better than scrolling through a component and finding : null} with no context ūüĎÄ

Wrapping Dependent Content

In React, our unit of reuse is usually a component so can we move this behaviour into a component?

const example = (
  <OnlyIf all={{ user, profile, otherData }}>
    only render this content if all of user, profile & otherData are defined
  </OnlyIf>
);

It turns out that this is actually a pretty simple component:

  1. determine if the all prop values are truthy
  2. only render the children if they are
interface OnlyIfProps<T> {
  all: T;
}

class OnlyIf<T> extends PureComponent<OnlyIfProps<T>> {
  render() {
    const { all, children } = this.props;

    let allValuesSpecified = true;
    Object.keys(all).forEach(
      key => (allValuesSpecified = allValuesSpecified && !!all[key])
    );

    return allValuesSpecified ? children : null;
  }
}

Lazy Rendering Content

The “ component above may be useful but there is an important scenario that is not covered: children attempting to use undefined values.

const example = (
  <OnlyIf all={{ user }}>
    <h1>{user.name}</h1> {/* <-- this will throw if user is undefined */}
  </OnlyIf>
);

In this case we shouldn’t even attempt to render the children if user is undefined. We cannot prevent it when we use the structure above but if we switch to a render props pattern then we can control when children are rendererd:

const example = (
  <OnlyIf all={{ user }}>{values => <h1>{values.user.name}</h1>}</OnlyIf>
);

We can update our component to support both scenarios by…

  1. accepting either ReactNode (the default) or (values: T) =&gt; ReactNode as our children
  2. identifying the function in render and invoking it
interface OnlyIfProps<T> {
  all: T;
  children: ReactNode | ((values: T) => ReactNode);
}

class OnlyIf<T> extends PureComponent<OnlyIfProps<T>> {
  render() {
    const { all, children } = this.props;

    let allValuesSpecified = true;
    Object.keys(all).forEach(
      key => (allValuesSpecified = allValuesSpecified && !!all[key])
    );

    if (!allValuesSpecified) return null;

    return typeof children === 'function' ? children(all) : children;
  }
}

Now we can accept either a render function or a component as the situation demands!

Is this a good idea?

So we absolutely can create “ but is it useful?

On the negative side, it is an unfamiliar component that may have unexpected effects for new developers.

On the other hand, it’s fairly self explanatory and is an improvement in general readability in my opinion.

Overall I think it’s a nice addition. It certainly beats the hell out of a 20 line ternary expression!

Advertisements

Higher-Order Components with React & TypeScript

Higher-order components are a great way of reusing common functionality in your react app.

TypeScript is a great way of making sure your react app can grow without you losing your mind.

So how can we use the two together?

Higher-Order Components

A higher-order component (HoC) is a function that accepts a component as an argument and returns a new component that has been enhanced in some way.

const EnhancedComponent = myHigherOrderComponent(WrappedComponent);

The enhanced component can add behaviour, manage state or in any other way modify WrappedComponent.

Injecting Props

A common pattern is for a higher-order component to provide some props to the wrapped component, moving the management of those props out of WrappedComponent and allowing it to focus on other concerns.

For example, connect(...)(WrappedComponent) in react-redux provides props to both expose redux state and to dispatch actions. withRouter(WrappedComponent) in react-router similarly injects routing-related props into WrappedComponent from the current route.

Getting the prop types right when injecting props can be a bit fiddly. We want:

  1. WrappedComponent to have new props injected automatically
  2. Injected props not to be required on the created EnhancedComponent
  3. Any other props on WrappedComponent to be forwarded from EnhancedComponent
  4. TypeScript to infer all of the above with no manual specification for the user

For example, let’s say we have a HoC that will manage the isExpanded state of an expander component. It will provide the following props to WrappedComponent

interface ExpanderProps {
  isExpanded: boolean;
  toggleExpanded(): void;
}

Our wrapped component will need to accept these props but it might define some others as well. Let’s say it has a title that needs to be specified and an optional className:

interface WrappedComponentProps {
  isExpanded: boolean;
  toggleExpanded(): void;
  title: string;
  className?: string;
}

note that you could (and should!) define this as WrappedComponentProps extends ExpanderProps... and avoid duplicating the prop definitions. I’ve left this as it is here for clarity

In this case we want both title and className to be available on EnhancedComponent:

const EnhancedComponent = withExpander(WrappedComponent);

const usage = (
  <EnhancedComponent
    title="The title"
    className="class-name">
    ...
  </EnhancedComponent>
);

The Wrapped Component

At this stage we have already defined the provided props as an interface and we have an example of what the wrapped component might look like. Let’s flesh that out a bit (and give it a more appropriate name):

interface ExpanderComponentProps extends ExpanderProps {
  title: string;
}

class ExpanderComponent extends PureComponent<ExpanderComponentProps> {
  render() {
    const { isExpanded, toggleExpanded, title, children } = this.props;

    return (
      <>
        <button onClick={toggleExpanded}>{title}</button>
        {isExpanded && children}
      </>
    );
  }
}

Fairly simple: render a button containing title that toggles the expanded state. If isExpanded=true then also render the children.

Create the Enhancer

Now we want to create the enhancer function that we can use to inject isExpanded and toggleExpanded. Our first requirement is that it accepts an argument of WrappedComponent where WrappedComponent accepts the props we want to inject. That function signature might look something like this:

function withExpander(WrappedComponent: ComponentType<ExpanderProps>) {
  //...
}

ComponentType is a react type that allows you to pass in either a component class or a stateless functional component that has props of T

The next requirement is that it returns a component that doesn’t require the ExpanderProps to be specified, which means that we need to provide them from the enhanced component. In this case we’re going to get those values from the state on the component but that’s not a requirement – they can come from anywhere.

Once we have the values we need we can pass them to WrappedComponent in the render method:

function withExpander(WrappedComponent: ComponentType<ExpanderProps>) {
  return class WithExpander extends PureComponent<{}, { isExpanded: boolean }> {
    render() {
      return <WrappedComponent
        {...this.state}
        toggleExpanded={this.toggleExpanded}
        />
    }

    private toggleExpanded = () => this.setState(state => ({ isExpanded: !state.isExpanded }));
  }
}

All right, nice and easy! Except… build failure!

const EnhancedComponent = withExpander(ExpanderComponent);
// Error!

Our ExpanderComponent requires a title prop; when we use it (as WrappedComponent) in withExpander we don’t specify the title!

We could make withExpander aware of the title prop but that’s not very useful for the future: there will likely be other props that need to be passed through and we don’t want to keep adding them to our HoC.

This brings us on to Requirement 3 above: any other props from the wrapped component should be forwarded from the enhanced component. In this case, we really want to have the title prop be exposed on EnhancedComponent.

The first step in getting to that point is to allow the WrappedComponent parameter of our HoC to accept props that aren’t on ExpanderProps. In fact, we need our wrapped component to accept props of both ExpanderProps and whatever else it wants.

We can introduce a generic type parameter to the HoC function to represent that combined props object:

function withExpander<TWrappedComponentProps extends ExpanderProps>(
  WrappedComponent: ComponentType<TWrappedComponentProps> ) {
  //...
}

That solves our build failure: withExpander will now accept any component as long as it has the two isExpanded and toggleExpanded props.

Sadly we’re not quite done yet though; try to use the enhanced component and you will see our next problem:

const EnhancedComponent = withExpander(ExpanderComponent);

const usage = <EnhancedComponent title="Some title" />;
// Error!

Another build failure, this time telling us that title does not exist on the enhanced component. We’ve managed to write our HoC so that it allows extra props but all it does is ignore them!

What we really want here is to create a new Props type that we can assign to our created component. TypeScript 2.8 includes 2 built-in types that are going to help us out:

  • Pick<T, U> that takes the props from T specified in U. e.g. Pick<ExpanderProps, ‘isExpanded’> creates a type with only the isExpanded property
  • Exclude<T, U> that takes everything from T except U. e.g. Exclude<‘one’ | ‘two’ | ‘three’, ‘two’>* creates a type 'one' | 'three'

By combining these with keyof we can build up the “all props that are on the inner component but excluding the ones we’re providing” type. We might want a better name though…

function withExpander<TWrappedComponentProps extends ExpanderProps>(WrappedComponent: ComponentType<TWrappedComponentProps>) {
  type WrappedComponentPropsExceptProvided = Exclude<keyof TWrappedComponentProps, keyof ExpanderProps>;
  // => 'title' | 'className'
  type ForwardedProps = Pick<TWrappedComponentProps, WrappedComponentPropsExceptProvided>;
  // => { title: string; className?: string }

  //...
}

Now that we know what our forwarded props should look like we can specify those on the component.

return class WithExpander extends PureComponent<
  ForwardedProps,
  { isExpanded: boolean }
> {
  render() {
    return (
      <WrappedComponent
        {...this.props}
        {...this.state}
        toggleExpanded={this.toggleExpanded}
      />
    );
  }

  //...
};

the additional spread of this.props onto WrappedComponent copies the externally-specified props onto the wrapped component

Now we can use our enhanced component as intended.

const EnhancedComponent = withExpander(ExpanderComponent);

const usage = (
  <EnhancedComponent title="title">
    <div>...</div>
  </EnhancedComponent>
);

As a bonus, TypeScript gives us Requirement 4 for free! Type inference means that we don’t have to specify any types explicitly in our usage of this HoC but we still have full type safety. Try removing title or adding an unknown property and your IDE will light up with compilation errors – thanks TypeScript! ‚ú®

Post-Logout Redirect with ASP.NET Core and ADFS 2016

Redirect after logout

When a user logs out from your app you have the option to log them out of the provider as well by redirecting the browser to the logout endpoint. By default this means that the user will end up sat on your providers “You have signed out” page – not brilliant.

You can, however, tell your provider to redirect back to your app once they’re done with logout by specifying a post_logout_redirect_uri.

For ASP.NET Core Identity you can specify this redirection as a parameter on the SignOutResult.

[Route("auth")]
public class AuthController
{
  [HttpPost("logout")]
  public IActionResult Logout() => new SignOutResult(
    OpenIdConnectDefaults.AuthenticationScheme,
    new AuthenticationProperties { RedirectUri = Url.Action(nameof(LogoutSuccess))});

  [HttpGet("logoutSuccess")]
  public IActionResult LogoutSuccess() => View();
}

Useless ADFS error messages

For ADFS 2016 you need to do a little bit more than just set the redirect URL. On first inspection you can see that the above will set the parameter in the ADFS URL but ADFS will silently ignore it and your user will sit forever on the ADFS sign-out page.

Digging into the event logs you will find the following error message:

The specified redirect URL did not match any of the OAuth client’s redirect URIs. The logout was successful but the client will not be redirected

If you’re unlucky, this wonderfully-misleading error message can take you down a rabbit hole of further configuration. It’s a shame, then, that no-one thought to expose something a little more accurate:

That redirect looks good but you need to specify id_token_hint or we’ll ignore you

Thanks ADFS!

Sending ID Token Hint

To be fair to ADFS, sending an id_token_hint is recommended by the spec. This parameter needs to be set to the id_token that was sent to your app when the user first logged in; provide this value and ADFS will happily redirect back to your app.

The only problem here is that you probably don’t still have that id_token. ASP.NET Core Identity uses the identity information to create an auth cookie and then (by default) discards it.

Happily, the OpenIdConnectOptions exposes a SaveTokens property to persist the received token to the auth cookie. Even better: the OIDC logout mechanism will automatically pick this up once enabled so you should be good to go as soon as you set the flag:

public class Startup {
  public void ConfigureServices(IServiceCollection services)
  {
    services.AddAuthentication()
      .AddOpenIdConnect(options => {
        options.SaveTokens = true;
        //...set other options
      });

    //...other service config
  }
}

This does have one important downside though: you’re now storing much more information in your auth cookie and that adds extra data to every client request, maybe even doubling the cookie size.

Whether or not this is a problem for your app is another decision – at least your logout redirect works now!

Stop Agonising Over Tiny Details

I recently started a new side project using React and – having not used React in anger before – wanted to get off on the right foot.

And by “on the right foot” I apparently decided that I meant “with the perfect folder structure for my code”.

Obviously we can all agree that folder structure is the most important predictor of code quality ¬†(<sarcasm/>) so I spent hours agonising over whether to separate ¬†components from screens or whether to group all actions together in an actions folder and a hundred other basically-irrelevant details. I read blog posts. I tried template project generators. I poured over a huge number of “sample” GitHub repos (every one different, of course).

To reiterate: this was for a new, greenfield side project. I spent hours of my limited time worrying about where to put all the code instead of…writing any of that code!

facepalm

Hence this post. This post sits here as a reminder to myself to STOP AGONISING OVER UNIMPORTANT THINGS.

And you know what? I changed the entire structure after a week anyway.

Finding Freedom in “JavaScript Fatigue”

A lot of people have spoken about “JavaScript fatigue”: the idea that there are so many new frameworks, tools and ideas available to the average JavaScript developer that it’s impossible to keep up. I thought I’d add my opinion.

When I started learning JavaScript it used to be that I would try to keep up with everything. I suspect now that I just didn’t know how much was out there, but it really felt like that was an acheivable target. I would make a real effort to not only read up on new frameworks & libraries but to try them out: maybe a quick tutorial, maybe a few introductory posts, maybe even a small project.

Now, things have changed and it is obvious to most of us that there is no way you can invest that much time in every new thing that comes out.

For me, this is not a bad thing. In fact, I find it pretty liberating.

The whole situation reminds me a little bit of when I first joined Twitter. I was following maybe 20 people and I would make a real effort to read every single tweet. Ridiculous, right? But still I tried. Then I started following more people and then more people and with every extra piece of content it became less and less realistic to get through everything.

So I let go. I had to.

I couldn’t keep up with everything so I stopped trying to do the impossible and learned to let the mass of information wash over me. If something particularly catches my eye then I can read up on it but if I miss something? Who really cares?

Nowadays it feels the same with JavaScript frameworks. I may never have a chance to get my hands dirty with everything that comes out. In fact, I may never even hear of some of them. But I don’t worry any more about trying to keep up and if something really is the next big thing… well, I’m pretty sure I’ll hear about it soon enough.

Cleaning up Resources using MutationObserver

Cleaning up resources?

Let’s say you’ve written a shiny new component in your favorite framework and somewhere along the way you’ve allocated a resource that cannot be automatically cleaned up by the browser.

Maybe you attached an event handler to the resize event on the window.  Maybe you passed a callback to a global object.  Whatever the case, you need to tidy up those resources at some point.

Easy enough, right? ¬†Put a dispose method on our object to clean up it’s leftovers and make sure it’s called before the object is discarded.

Problem solved?

Problem not quite solved

What if, for whatever reason, your component doesn’t have control over the parent? ¬†You could trust that the user will do the right thing and call dispose for you but you can’t¬†guarantee it.

As an alternative, can we automatically clean up our resources as soon as our containing DOM element is removed?

Yes.  Yes we can.

Using MutationObserver

The MutationObserver API (which has pretty great browser support) lets you listen to changes made to a DOM node and react to it.  We can use it here to perform our cleanup.

When we create an instance of MutationObserver we specify a callback that gets details of changes made to the parent.  If those changes include the removal of our target element then we can call dispose.

Here we are observing the parent of our target node, not the node itself (which would not be notified if removed).  We need to specify { childList: true } as the second parameter to be notified of additions and removals of child items.

Disposing the Observer

Finally, we need to make sure that the observer itself doesn’t cause a memory leak! ¬†The observer is connected to the parentElement¬†which (we assume) will still be hanging around, so we need to make sure that we disconnect¬†it as part of disposal.

With everything pulled together the final version looks like this…

Supporting SignalR Client Handlers after Connection Start

(Yes, that is a pretty specific post title but then this is a pretty specific problem…)

In general, when you create a new SignalR connection you are obliged to have already defined any of your handlers on the connection.yourHubName.client object. This allows SignalR to discover those handlers and hook them up to the incoming messages.

Problem: Multiple connection sources

This approach is fine as long as you have a single place from which you are starting your connection but what if you have 2 hubs, 2 separate client handlers…2 of everything?

They will both automatically share a SignalR connection so you can end up with a bit of a race condition where the first handler to start the connection will be the only handler registered. ¬†Imagine the following handlers…

function MyFirstHandler() {
  //assign the handler
  $.connection.myHub1.client.method1= function() { ... };

  //start the connection
  $.connection.myHub1.connection.start();
}

function MySecondHandler() {
  //assign the handler
  $.connection.myHub2.client.method2= function() { ... };

  //start the connection
  $.connection.myHub2.connection.start();
}

//...some time later...
new MyFirstHandler()
//...and even later still...
new MySecondHandler()

By the time we create MySecondHandler we have already created the connection and so method2 is not attached and will never be invoked.

Solution: Proxy implementation

We can work around this by replacing the connection.yourHubName.client object (normally just a POJO) with something that is aware of the available server methods. ¬†The new client then¬†exposes stubs to which SignalR can connect before our¬†MySecondHandler¬†can provide the “real” handler implementations.

//before creating any handlers
$.connection.myHub1.client = new SignalRClient(['method1','otherHandler']);
$.connection.myHub2.client = new SignalRClient(['method2']);

The SignalRClient implementation has 3 requirements for each named handler:

  1. Always return a valid handler function for SignalR to bind, even if the real handler hasn’t been assigned¬†yet
  2. If the real handler has been assigned, invoke that when the handler is invoked (with all args etc.)
  3. Allow client.myHandler = function(){} assignments for compatibility with existing code

The last requirement means that we need to use Object.defineProperty with custom getter and setter implementations.  The getter should always return a stub method; the setter should store the real handler; and the stub method should invoke the real handler (if assigned).

function SignalRClient(methods) {
	this._handlers = {};
	methods.forEach(this.registerHandler.bind(this));
}

SignalRClient.prototype.invokeHandler = function(name) {
	var handler = this._handlers[name];
	if (handler) {
		var handlerArgs = Array.prototype.slice.call(arguments, 1);
		handler.apply(this, handlerArgs);
	}
}

SignalRClient.prototype.registerHandler = function(name) {
	var getter = this.invokeHandler.bind(this, name);
	Object.defineProperty(this, name, {
		enumerable: true,
		get: function() { return getter },
		set: function (value) { this._handlers[name] = value; }.bind(this)
	});
}

Note that our defined properties must also be marked as enumerable so that the SignalR code picks up on them when it attempts to enumerate the client handler methods.

Now – provided we know the available methods up front – we can start the connection whenever we like and assign our handlers later!