Skip to content
Prev Previous commit
Next Next commit
Don't render container for server side only components
  • Loading branch information
Gustav Tonér committed Jan 15, 2018
commit 71c65770d2431f0da38824add7884bd506d374e5
5 changes: 5 additions & 0 deletions src/React.Core/ReactComponent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,11 @@ public virtual string RenderHtml(bool renderContainerOnly = false, bool renderSe
? string.Format("ReactDOMServer.renderToStaticMarkup({0})", GetComponentInitialiser())
: string.Format("ReactDOMServer.renderToString({0})", GetComponentInitialiser());
html = _environment.Execute<string>(reactRenderCommand);

if (renderServerOnly)
{
return html;
}
}

string attributes = string.Format("id=\"{0}\"", ContainerId);
Expand Down
41 changes: 40 additions & 1 deletion tests/React.Tests/Core/ReactComponentTest.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/*
/*
* Copyright (c) 2014-Present, Facebook, Inc.
* All rights reserved.
*
Expand Down Expand Up @@ -122,6 +122,45 @@ public void RenderHtmlShouldWrapComponentInCustomElement()
Assert.Equal(@"<span id=""container"">[HTML]</span>", result);
}

[Fact]
public void RenderHtmlShouldNotRenderComponentWhenContainerOnly()
{
var config = new Mock<IReactSiteConfiguration>();
config.Setup(x => x.UseServerSideRendering).Returns(true);
var environment = new Mock<IReactEnvironment>();
environment.Setup(x => x.Execute<bool>("typeof Foo !== 'undefined'")).Returns(true);
environment.Setup(x => x.Execute<string>(@"ReactDOMServer.renderToString(React.createElement(Foo, {""hello"":""World""}))"))
.Returns("[HTML]");

var component = new ReactComponent(environment.Object, config.Object, "Foo", "container")
{
Props = new { hello = "World" },
ContainerTag = "span"
};
var result = component.RenderHtml(true, false);

Assert.Equal(@"<span id=""container""></span>", result);
}

[Fact]
public void RenderHtmlShouldNotWrapComponentWhenServerSideOnly()
{
var config = new Mock<IReactSiteConfiguration>();
config.Setup(x => x.UseServerSideRendering).Returns(true);
var environment = new Mock<IReactEnvironment>();
environment.Setup(x => x.Execute<bool>("typeof Foo !== 'undefined'")).Returns(true);
environment.Setup(x => x.Execute<string>(@"ReactDOMServer.renderToStaticMarkup(React.createElement(Foo, {""hello"":""World""}))"))
.Returns("[HTML]");

var component = new ReactComponent(environment.Object, config.Object, "Foo", "container")
{
Props = new { hello = "World" },
};
var result = component.RenderHtml(false, true);

Assert.Equal(@"[HTML]", result);
}

[Fact]
public void RenderHtmlShouldAddClassToElement()
{
Expand Down