Tag Archives: React

A C# Developer’s Guide to: ReactJS – Part 2 – Moving Controls

Following on from my previous post, I’m going to extend our ReactJS application by adding some boxes, and allowing the user to re-arrange them on the screen.

Concepts

There are two key concepts to consider when working with React, and we’ll cover one of them in this post; that is: state.

React has a special property of each component known as state. If you use that to bind any of the UI to, then React will refresh that component when the state changes.

Moving a UI Element

Okay – that sounds great, but how would we do this in practice?

Imagine that you have a HTML box drawn on the screen; you might have something like this:

<div style="height:100px; width:200px; background:#0000FF" />

We can draw a box. If you use this code, then your box will be on the top left of the screen; so we can tell it not to be by specifying the left and top; let’s try defining a CSS style:

<div style="left:10px; top:20px;height:100px; width:200px; background:#0000FF" />

With React, we can set those values to a value derived from the state; for example:

render() {
    const top = this.state.newY;
    const left = this.state.newX;

    const myStyle = {
        height: '100px',
        width: '200px', 
        top: `calc(${top}px)`,
        left: `calc(${left}px)`, 
        borderStyle: 'solid',
        borderColor: 'blue', 
        position: 'absolute',
        zIndex: 1,
        background: 'blue'
    };

    return ( 
        <div> 
            <div style={myStyle}>source</div>
        </div>
    );
}

What this means is that every time I change the state values, the values in the style will update.

To illustrate this, if we write a React application like this (only the timeout function is new):

render() {
    const top = this.state.newY;
    const left = this.state.newX;
    const myStyle = {
        height: '100px',
        width: '200px', 
        top: `calc(${top}px)`,
        left: `calc(${left}px)`, 
        borderStyle: 'solid',
        borderColor: 'blue', 
        position: 'absolute',
        zIndex: 1,
        background: 'blue'
    };

    setTimeout(() => {
        this.setState({newX: this.state.newX + 1, newY: this.state.newY + 1});
    }, 50);

    return ( 
        <div> 
            <div style={myStyle}></div>
        </div>
    );
}

We can make out box move diagonally across the screen:

Screenshot included because you couldn’t possibly imaging what a blue rectangle looks like.

Start the app using VS Code

A quick note on VS Code. If you select Terminal -> New from the menu, you can run the React application directly from the IDE; and the best part is that if there’s something already running on the port, VS Code will just give you a new one:

Short Walks – Navigating in ReactJs

When you start using the React sample templates, one thing that you’ll notice is the navigation menu; it tends to look like this:

<div className='navbar-collapse collapse'>
    <ul className='nav navbar-nav'>
        <li>
            <NavLink to={ '/' } exact activeClassName='active'>
                <span className='glyphicon glyphicon-home'></span> Home
            </NavLink>
        </li>

After messing around for a while, you’ll probably think: now I need to navigate somewhere from within the code of the tsx/jsx file. Turns out you need to use `.push()`:

import { NavLink } from 'react-router-dom';

. . .

doSomething()
.then(output => {
    this.props.history.push('/timbuktu');
});

Not exactly intuitive. And even less intuitive is if you want to go back. You’re thinking it must be `.pop()`? So was I; it’s actually:

import { NavLink } from 'react-router-dom';

. . .

doSomething()
.then(output => {
    this.props.history.goBack();
});

Adding ReactJS to an existing Asp.Net Core 2 Application

I’ve recently been playing around with writing an Asp.Net Core 2 app from scratch. If you’re interested, you can view my exploits here.

I came across an interesting issue, which was that I wanted to search an in memory set of data, and I wanted the screen to update as I searched. React sounds like the perfect tool for this; and this article describes how to integrate a React view (JSX file) into an MVC view.

(Note that it doesn’t cover implementing the search function – that will be the subject of a later post when and if I work out how to do it.)

Set-up

After you’ve created your Asp.Net Core 2 application, the first step is to install React; which is a NuGet package:

Install-Package React.AspNet -Source nuget.org

There are some code tweaks that are needed; the first is in startup.cs (which basically tells Asp to use React, and how to do so):

services.AddTransient< …
 
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddReact();
 
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
app.UseReact(config =>
{
    
});
 
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();

You’ll need to slightly change the signature of ConfigureServices, too:

public IServiceProvider ConfigureServices(IServiceCollection services)
{
. . . 
    return services.BuildServiceProvider();
}

The next thing is to make React available to your views; in ViewImports.cshtml:

@using UsefulSites.Web
@using UsefulSites.Web.Models
@using UsefulSites.Web.ViewModels
@using React.AspNet
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

React Code

Next step is to create the ReactJs file:

class SearchBox extends React.Component {
    render() {
        return (
            <div className="search-container">
                <textarea>
                    Search Text
                </textarea>    
            </div>
        );
    }
}
 
ReactDOM.render(
    <SearchBox />,
    document.getElementById('content')
);

Then change the HTML file:

<div class="row">
    <div class="jumbotron">
        <div id="content"></div>
        <script crossorigin src="https://cdnjs.cloudflare.com/ajax/libs/react/16.4.0/umd/react.development.js"></script>
        <script crossorigin src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.4.0/umd/react-dom.development.js"></script>
        <script src="@Url.Content("~/js/search.jsx")"></script>
    </div>

As you can see, the React script references the div named “content” specifically.

References

https://reactjs.net/getting-started/aspnetcore.html

https://reactjs.net/getting-started/download.html