Last active
May 1, 2018 11:23
-
-
Save charlieanstey/64ec831882727f0e0f0a02f9d97350e8 to your computer and use it in GitHub Desktop.
React component hydrator #C# #React
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Newtonsoft.Json; | |
using React; | |
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace Umbraco.CMS.Helpers | |
{ | |
/// <summary> | |
/// Service helper to provide React Component config(s) required to hydrate on client-side | |
/// </summary> | |
public class ReactComponentHydrator | |
{ | |
/// <summary> | |
/// List of all components instantiated in the request | |
/// </summary> | |
protected readonly IList<IReactComponent> _components = new List<IReactComponent>(); | |
public ReactComponentHydrator() | |
{ | |
} | |
/// <summary> | |
/// Adds a React Component to an internal list to be processed | |
/// </summary> | |
/// <param name="reactComponent"></param> | |
public void Add(IReactComponent reactComponent) | |
{ | |
_components.Add(reactComponent); | |
} | |
public IList<ReactComponentHydratorConfig> GetComponentConfigs() | |
{ | |
return _components.Select(GenerateReactComponentHydratorConfig).ToList(); | |
} | |
/// <summary> | |
/// Returns the config necessary for the client-side to hydrate the React Component | |
/// </summary> | |
/// <param name="reactComponent"></param> | |
/// <returns>ReactComponentHydratorConfig</returns> | |
protected ReactComponentHydratorConfig GenerateReactComponentHydratorConfig(IReactComponent reactComponent) | |
{ | |
return new ReactComponentHydratorConfig | |
{ | |
ComponentName = reactComponent.ComponentName, | |
ContainerId = reactComponent.ContainerId, | |
Props = reactComponent.Props | |
}; | |
} | |
} | |
[Serializable] | |
public class ReactComponentHydratorConfig | |
{ | |
/// <summary>Raw props for this component</summary> | |
protected object _props; | |
/// <summary>JSON serialized props for this component</summary> | |
protected string _serializedProps; | |
/// <summary>Gets or sets the name of the component</summary> | |
[JsonProperty("name")] | |
public string ComponentName { get; set; } | |
/// <summary> | |
/// Gets or sets the unique ID for the DIV container of this component | |
/// </summary> | |
[JsonProperty("containerId")] | |
public string ContainerId { get; set; } | |
/// <summary>Gets or sets the props for this component</summary> | |
[JsonProperty("props")] | |
public object Props | |
{ | |
get | |
{ | |
return this._props; | |
} | |
set | |
{ | |
this._props = value; | |
this._serializedProps = JsonConvert.SerializeObject(value); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment