In one of the last posts, we saw how we can make a simple chat withASP.NET Core SignalR and Angular 5. This time, we will use the same code from the backend and swap Angular with React on the frontend.
There is also a post about making a simple SignalR app with pure ASP.NET Core stack, using Razor Pages with vanilla JavaScript on the client –ASP.NET Core SignalR simple chat.
Most of the code should be the same, and because of that, we will focus mostly on the client side.
We will usecreate-react-app,which is an officially supported way to create SPA applications with React. It has no configuration, but it does use Webpack and Babel under the hood.
It is easy to use and requires no configuration, to be precise, you can’t configure it. It comes with 4 predefined scripts:
We will use only the first one during this post.
We will use the same server-side code as we did with oursimple chat with Angular 5.
Let’s first create a new empty React application:
Now we can immediately add SignalR npm package:
Let’s add our Chat component now:
We are using the same properties as we did with Angular chat. We only need nick, message, messages and HubConnection.
First is the user’s nickname, second is the current message being typed to the input,messages are for all the messages that we receive from the server.
The user’s nickname and the connection to the server we only need to set up once, at the start. Hence, we will add the componentDidMount lifecycle method:
After we set up the nick and the HubConnection object, we should try to establish the connection with the Server:
After that is achieved, we can now start listening for the events from the server. We will just extend our code inside of setState’s callback. We will add this code snippet:
Let’s take a look at our Chat component, how it looks at the moment:
That seems fine. Now, we need to add the logic for sending messages to the server. Also, we need to show the actual messages in the view and the button for sending messages.
We will keep the method for sending messages simple:
After we sent the message, we can clear out the input – message property.
Here is the view to finish our Chat component:
You can find the code sample on GitHub:ASP.NET Core SignalR Chat
You can find step by step (commits) on this repository:AspNetCoreSignalR_React
Why is ASP.NET Core good for Enterprise applications
ASP.NET Core Dependency Injection – Cannot consume scoped service
Hosting ASP.NET Core on Heroku (with Docker&CircleCI) for free
ASP.NET Core 2 – Global Model validation
ASP.NET Core – Unit testing IAuthorizationService and dependencies inside of your controller
ASP.NET Core – InvalidOperationException: Cannot find compilation library location for package ‘Microsoft.Win32.Registry’
Software Consultant interested and specialising in ASP.NET Core, C#, JavaScript, Angular, React.js.
Categories
Tags