Naučite graditi aplikaciju React chat za 10 minuta - udžbenik React JS

U ovom članku pokazat ću vam najlakši mogući način za stvaranje aplikacije za chat pomoću React.js-a. To će biti učinjeno u potpunosti bez koda na strani poslužitelja, jer ćemo pustiti da Chatkit API obrađuje pozadinu.

Pretpostavljam da znate osnovni JavaScript i da ste već susreli malo React.js-a. Osim toga, nema preduvjeta.

Napomena: Ovdje sam također kreirao besplatni cjeloviti tečaj o tome kako stvoriti aplikaciju za chat React.js:

Ako slijedite ovaj vodič, na kraju ćete završiti s vlastitom aplikacijom za chat, koju možete dalje nadograditi ako želite.

Započnimo!

Korak 1: Razbijanje korisničkog sučelja na komponente

React se temelji na komponentama, tako da prvo što želite učiniti prilikom stvaranja aplikacije je razbiti njezino korisničko sučelje na komponente.

Krenimo crtanjem pravokutnika oko cijele aplikacije. Ovo je vaša korijenska komponenta i zajednički predak svim ostalim komponentama. Nazovimo to App:

Nakon što definirate svoju korijensku komponentu, trebate si postaviti sljedeće pitanje:

Koju izravnu djecu ima ova komponenta?

U našem slučaju ima smisla dati mu tri podređene komponente, koje ćemo nazvati sljedeće:

  • Title
  • MessagesList
  • SendMessageForm

Nacrtajmo pravokutnik za svaku od ovih:

Ovo nam daje lijep pregled različitih komponenata i arhitekture iza naše aplikacije.

Mogli smo se nastaviti pitati koju djecu ove komponente opet imaju. Stoga smo mogli razbiti korisničko sučelje na još više komponenata, na primjer pretvaranjem svake poruke u svoje komponente. Međutim, ovdje ćemo se zaustaviti radi jednostavnosti.

Korak 2: Postavljanje baze kodova

Sada ćemo morati postaviti naše spremište. Upotrijebit ćemo najjednostavniju moguću strukturu: datoteku * index.html * s vezama na JavaScript datoteku i tablicu stilova. Uvozimo i Chatkit SDK i Babel, koji se koriste za transformiranje našeg JSX-a:

Evo Scrimba igrališta s konačnim kodom za tutorial. Preporučio bih vam da ga otvorite na novoj kartici i poigrate se s njim kad god se osjećate zbunjeno.

Možete i preuzeti projekt Scrimba kao .zip datoteku i pokrenuti jednostavni poslužitelj da ga pokrenete i pokrenete lokalno.

Korak 3: Stvaranje korijenske komponente

S postavljenim spremištem, možemo započeti s pisanjem React koda, što ćemo učiniti unutar datoteke * index.js *.

Počnimo s glavni sastojak, App. Ovo će biti naša jedina "pametna" komponenta, jer će obrađivati ​​podatke i vezu s API-jem. Evo osnovne postavke za nju (prije nego što smo dodali bilo kakvu logiku):

 class App extends React.Component { render() { return ( ) } } 

Kao što možete vidjeti, to jednostavno čini se troje djece su: , , i komponente.

Učinit ćemo to ipak malo složenijim, jer će poruke chata morati biti pohranjene unutar stanja ove Appkomponente. To će nam omogućiti pristup porukama this.state.messagesi prosljeđivanje ih ostalim komponentama.

Počet ćemo s upotrebom lažnih podataka kako bismo mogli razumjeti tijek podataka aplikacije. Zatim ćemo to kasnije zamijeniti stvarnim podacima iz API-ja Chatkit.

Stvorimo DUMMY_DATAvarijablu:

 const DUMMY_DATA = [ { senderId: "perborgen", text: "who'll win?" }, { senderId: "janedoe", text: "who'll win?" } ] 

Zatim ćemo te podatke dodati u stanje Appi proslijediti ih MessageListkomponenti kao potporu.

 class App extends React.Component { constructor() { super() this.state = { messages: DUMMY_DATA } } render() { return ( ) } } 

Ovdje inicijaliziramo stanje u constructori također prelazimo this.state.messagesna MessageList.

Imajte na umu da pozivamo super()konstruktor. To morate učiniti ako želite stvoriti komponentu sa statusom.

Korak 4: Prikazivanje lažnih poruka

Pogledajmo kako možemo prikazati ove poruke u MessageListkomponenti. Evo kako to izgleda:

 class MessageList extends React.Component { render() { return ( 
    
    {this.props.messages.map(message => { return (
  • {message.senderId} {message.text}
  • ) })}
) } }

Ovo je takozvana glupa komponenta. Potreban je jedan rekvizit messageskoji sadrži niz objekata. I onda mi samo renderiranje out texti senderIdsvojstva od objekata.

S našim lažnim podacima koji se ulijevaju u ovu komponentu, prikazat će se sljedeće:

Dakle, sada imamo osnovnu strukturu za našu aplikaciju, a također možemo i prikazivati ​​poruke. Odličan posao!

Zamijenimo sada naše lažne podatke stvarnim porukama iz chat sobe!

Korak 5: Dohvaćanje API-ključeva iz Chatkita

Da bismo dobili poruke za dohvaćanje, morat ćemo se povezati s API-jem Chatkit. Da bismo to učinili, moramo dobiti API ključeve.

U ovom trenutku želim vas ohrabriti da slijedite moje korake kako biste mogli pokrenuti i pokrenuti vlastiti program za chat. Možete koristiti moje igralište Scrimba kako biste testirali vlastite API ključeve.

Start by creating a free account here. Once you’ve done that you’ll see your dashboard. This is where you create new Chatkit instances. Create one and give it whatever name you want:

Then you’ll be navigated to your newly created instance. Here you’ll need to copy four values:

  • Instance Locator
  • Test Token Provider
  • Room id
  • Username

We’ll start with the Instance Locator:

You can copy using the icon on the right side of the Instance Locator.

You can copy using the icon on the right side of the Instance Locator.

And if you scroll a bit down you’ll find the Test Token Provider:

The next step is to create a User* *and a Room, which is done on the same page. Note that you’ll have to create a user first, and then you’ll be able to create a room, which again gives you access to the room identifier.

So now you’ve found your four identifiers. Well done!

However, before we head back to the codebase, I want you to manually send a message from the Chatkit dashboard as well, as this will help us in the next chapter.

Here’s how to do that:

This is so that we actually have a message to render out in the next step.

Step 6: Rendering real chat messages

Now let’s head back to our index.js file and store these four identifiers as variables at the top of our file.

Here are mine, but I’d encourage you to create your own:

 const instanceLocator = "v1:us1:dfaf1e22-2d33-45c9-b4f8-31f634621d24" const testToken = "//us1.pusherplatform.io/services/chatkit_token_provider/v1/dfaf1e22-2d33-45c9-b4f8-31f634621d24/token" const username = "perborgen" const roomId = 9796712 

And with that in place, we’re finally ready to connect with Chatkit. This will happen in the App component, and more specifically in the componentDidMount method. That’s the method you should use when connecting React.js components to API’s.

First we’ll create a chatManager:

 componentDidMount() { const chatManager = new Chatkit.ChatManager({ instanceLocator: instanceLocator, userId: userId, tokenProvider: new Chatkit.TokenProvider({ url: testToken }) }) 

… and then we’ll dochatManager.connect() to connect with the API:

 chatManager.connect().then(currentUser => { currentUser.subscribeToRoom({ roomId: roomId, hooks: { onNewMessage: message => { this.setState({ messages: [...this.state.messages, message] }) } } }) }) } 

This gives us access to the currentUser object, which is the interface for interacting with the API.

Note: As we’ll need to usecurrentUser later on, well store it on the instance by doing this.currentUser = ``currentUser.

Then, we’re calling currentUser.subscribeToRoom() and pass it our roomId and an onNewMessage hook.

The onNewMessage hook is triggered every time a new message is broadcast to the chat room. So every time it happens, we’ll simply add the new message at the end of this.state.messages.

This results in the app fetching data from the API and then rendering it out on the page.

This is awesome, as we now have the skeleton for our client-server connection.

Woohoo!

Step 7: Handling user input

The next thing we’ll need to create is the SendMessageForm component. This will be a so-called controlled component, meaning the component controls what’s being rendered in the input field via its state.

Take a look at the render() method, and pay special attention to the lines I’ve highlighted:

 class SendMessageForm extends React.Component { render() { return (    ) } } 

We’re doing two things:

  1. Listening for user inputs with the onChange event listener, so that we can

    trigger the handleChange method

  2. Setting the value of the input field explicitly using this.state.message

The connection between these two steps is found inside the handleChange method. It simply updates the state to whatever the user types into the input field:

 handleChange(e) { this.setState({ message: e.target.value }) } 

This triggers a re-render, and since the input field is set explicitly from the state using value={this.state.message}, the input field will be updated.

So even though the app feels instant for the user when they type something into the input field, the data actually goes via the state before React updates the UI.

To wrap up this feature, we need to give the component a constructor. In it, we’ll both initialize the state and bind this in the handleChange method:

 constructor() { super() this.state = { message: '' } this.handleChange = this.handleChange.bind(this) } 

We need to bind the handleChangemethod so that we’ll have access to the this keyword inside of it. That’s how JavaScript works: the this keyword is by default undefined inside the body of a function.

Step 8: Sending messages

Our SendMessageForm component is almost finished, but we also need to take care of the form submission. We need fetch the messages and send them off!

To do this we’ll hook a handleSubmit even handler up with the onSubmit event listener in the .

 render() { return (    ) } 

As we have the value of the input field stored in this.state.message, it’s actually pretty easy to pass the correct data along with the submission. We’ll

simply do:

 handleSubmit(e) { e.preventDefault() this.props.sendMessage(this.state.message) this.setState({ message: '' }) } 

Here, we’re calling the sendMessage prop and passing in this.state.message as a parameter. You might be a little confused by this, as we haven’t created the sendMessage method yet. However, we’ll do that in the next section, as that method lives inside the App component. So don’t worry!

Secondly, we’re clearing out the input field by setting this.state.message to an empty string.

Here’s the entire SendMessageForm component. Notice that we’ve also bound this to the handleSubmit method:

 class SendMessageForm extends React.Component { constructor() { super() this.state = { message: '' } this.handleChange = this.handleChange.bind(this) this.handleSubmit = this.handleSubmit.bind(this) } handleChange(e) { this.setState({ message: e.target.value }) } handleSubmit(e) { e.preventDefault() this.props.sendMessage(this.state.message) this.setState({ message: '' }) } render() { return (    ) } } 

Step 9: Sending the messages to Chatkit

We’re now ready so send the messages off to Chatkit. That’s done up in the App component, where we’ll create a method called this.sendMessage:

 sendMessage(text) { this.currentUser.sendMessage({ text: text, roomId: roomId }) } 

It takes one parameter (the text) and it simply calls this.currentUser.sendMessage().

The final step is to pass this down to the component as a prop:

 /* App component */ render() { return ( ) } 

And with that, we’ve passed down the handler so that SendMessageForm can invoke it when the form is submitted.

Step 10: Creating the Title component

To finish up, let’s also create the Title component. It’s just a simple functional component, meaning a function which returns a JSX expression.

 function Title() { return 

My awesome chat app

}

It’s a good practice to use functional components, as they have more constraints than class components, which makes them less prone to bugs.

The result

And with that in place you have your own chat application which you can use to chat with your friends!

Give yourself a pat on the back if you’ve coded along until the very end.

If you want to learn how to build further upon this example, then check out my free course on how to create a chat app with React here.

Thanks for reading and happy coding :)