Impara a costruire un'app di chat react in 10 minuti - React JS Tutorial (2023)

Impara a costruire un'app di chat react in 10 minuti - React JS Tutorial (1)

In questo articolo, ti mostrerò il modo più semplice possibile per creare un'applicazione di chat utilizzando React.js.Sarà fatto interamente senza codice lato server, poiché lasceremoCHATKIT APIGestisci il back-end.

Suppongo che tu conosca JavaScript di base e che tu abbia mai incontrato un po 'di react.js prima.A parte questo, non ci sono prerequisiti.

Nota: ho anche creato un corso gratuito a figura interaCome creare un'app di chat React.js qui:

Se segui questo tutorial, finirai con la tua applicazione di chat alla fine, su cui puoi costruire ulteriormente se desideri.

Iniziamo!

Passaggio 1: rompere l'interfaccia utente in componenti

React è costruito attorno ai componenti, quindi la prima cosa che vuoi fare quando crei un'app è di interrompere l'interfaccia utente in componenti.

Cominciamo disegnando un rettangolo attorno all'intera app.Questo è il tuo componente radicale e l'antenato comune per tutti gli altri componenti.ChiamiamoloApp:

Impara a costruire un'app di chat react in 10 minuti - React JS Tutorial (2)

Dopo aver definito il tuo componente principale, devi porsi la seguente domanda:

Quali bambini diretti ha questo componente?

Nel nostro caso, ha senso dargli tre componenti per bambini, che chiameremo quanto segue:

  • Titolo
  • Elenco dei messaggi
  • SendMessageForm

Disegniamo un rettangolo per ciascuno di questi:

Impara a costruire un'app di chat react in 10 minuti - React JS Tutorial (3)

Questo ci dà una bella panoramica dei diversi componenti e dell'architettura dietro la nostra app.

Avremmo potuto continuare a chiederci quali bambini hanno di nuovo questi componenti.Quindi avremmo potuto infrangere l'interfaccia utente in ancora più componenti, ad esempio trasformando ciascuno dei messaggi in propri componenti.Tuttavia, ci fermeremo qui per motivi di semplicità.

Passaggio 2: impostare la base di codice

Ora dovremo configurare il nostro repository.Useremo la struttura più semplice possibile: un file *indice.html *con collegamenti a un file javascript e un foglio di stile.Stiamo anche importando Chatkit SDK e Babele, che viene utilizzato per trasformare il nostro JSX:

Impara a costruire un'app di chat react in 10 minuti - React JS Tutorial (4)

Ecco un parco giochi Scrimbacon il codice finale per il tutorial.Ti consiglierei di aprirlo in una nuova scheda e giocarci ogni volta che ti senti confuso.

Impara a costruire un'app di chat react in 10 minuti - React JS Tutorial (5)

In alternativa, puoi scaricare il progetto Scrimba come file .zip ed eseguire un sempliceserver per farlo funzionare localmente.

Passaggio 3: creazione del componente radice

Con il repository in atto, siamo in grado di iniziare a scrivere un codice React, che faremo all'interno del file *index.js *.

Cominciamo con il componente principale,App.Questo sarà il nostro unico componente "intelligente", in quanto gestirà i dati e la connessione con l'API.Ecco la configurazione di base per questo (prima di aggiungere qualsiasi logica):

L'app di classe estende react.component {render () {return (
)}

Come puoi vedere, rende semplicemente tre bambini: il,, e ilcomponenti.

Lo renderemo un po 'più complesso, poiché i messaggi di chat dovranno essere archiviati all'interno delstatodi questoAppcomponente.Questo ci consentirà di accedere ai messaggithis.state.Messages, e quindi passarli in giro ad altri componenti.

Inizieremo con i dati fittizi in modo da poter comprendere il flusso di dati dell'app.Quindi lo scambieremo con dati reali daCapannaAPI più tardi.

Creiamo unDummy_datavariabile:

cost dammy_data = [{Senderid: "Perborgen", testo: "Chi vincerà?"}, {Senderid: "Janedoe", testo: "Chi vincerà?"}]

Quindi aggiungeremo questi dati allo stato diAppe passalo alMessagelistacomponente come prop.

L'app di classe estende react.component {costructor () {super () this.state = {Messaggi: dammy_data}} render () {return (
< /div>)}}

Qui, stiamo inizializzando lo stato nelcostruttoreE stiamo anche passandothis.state.Messagesgiù versoMessagelista.

Nota che stiamo chiamandosuper()nel costruttore.Devi farlo se vuoi creare un componente statale.

Passaggio 4: rendering di messaggi fittizi

Vediamo come possiamo rendere questi messaggi inMessagelistacomponente.Ecco come appare:

Class Messagelist estende react.component {render () {return (
    {this.props.messages.map (message => {return (
  • {message.senderid}
    {message.text}
  • )})}
)}}

Questo è un cosiddetto stupido componente.Ci vuole un sostegno,messaggi, che contiene una serie di oggetti.E poi stiamo semplicemente rendendo fuori iltestoEcentriProprietà dagli oggetti.

Con i nostri dati fittizi che fluiscono in questo componente, renderà quanto segue:

Impara a costruire un'app di chat react in 10 minuti - React JS Tutorial (6)

Quindi ora abbiamo la struttura di base per la nostra app e siamo anche in grado di eliminare i messaggi.Ottimo lavoro!

Ora sostituiamo i nostri dati fittizi con i messaggi reali da una chat room!

Passaggio 5: recupero degli api-chiavi da chatkit

Per ricevere messaggi di recupero, dovremo connetterci con l'API Chatkit.E per farlo, dobbiamo ottenere le chiavi API.

A questo punto, voglio incoraggiarti a seguire i miei passi in modo da poter ottenere la tua applicazione di chat attivo e funzionante.Puoi usare il mioScrimba PlaygroundPer testare le tue chiavi API.

Inizia creando un gratuitoaccount qui.Una volta che hai fatto, vedrai la tua dashboard.Qui è dove crei nuove istanze di chatkit.Crea uno e dai qualsiasi nome tu voglia:

Impara a costruire un'app di chat react in 10 minuti - React JS Tutorial (7)

Quindi verrai navigato per l'istanza appena creata.Qui dovrai copiare quattro valori:

  • Localizzatore di istanza
  • Test Token Provider
  • ID stanza
  • Nome utente

Inizieremo con ilLocalizzatore di istanza:

Impara a costruire un'app di chat react in 10 minuti - React JS Tutorial (8)

È possibile copiare usando l'icona sul lato destro del localizzatore di istanza.

E se scorri un po 'verso il basso troverai ilTest Token Provider:

Impara a costruire un'app di chat react in 10 minuti - React JS Tutorial (9)

Il prossimo passo è creare unUtente* * e aCamera, che viene fatto sulla stessa pagina.Nota che dovrai creare un utentePrimo, e poi sarai in grado di creare una stanza, che ti dà di nuovo accesso all'identificatore della stanza.

Impara a costruire un'app di chat react in 10 minuti - React JS Tutorial (10)

Quindi ora hai trovato i tuoi quattro identificatori.Ben fatto!

Tuttavia, prima di tornare alla base di codice, voglio che tu invii manualmente un messaggio anche dalla dashboard di Chatkit, poiché questo ci aiuterà nel prossimo capitolo.

Ecco come farlo:

Impara a costruire un'app di chat react in 10 minuti - React JS Tutorial (11)

Questo è così che abbiamo effettivamente un messaggio da rendere fuori nel passaggio successivo.

Passaggio 6: rendering di veri messaggi di chat

Ora torniamo al nostroindice.jsFile e archivia questi quattro identificatori come variabili nella parte superiore del nostro file.

Ecco i miei, ma ti incoraggio a creare il tuo:

const instancelocator = "V1: US1: DFAF1E22-2D33-45C9-B4F8-31F634621D24" const TesToken = "https://us1.pusherplatform.io/services/chatkit_token_proudider/v1/dfaf1e222d3-45c9-b4f8-31d 24/token "const username = "perborgen" const roomid = 9796712

E con questo in atto, siamo finalmente pronti a connetterci con Chatkit.Questo accadrà nelAppcomponente e più specificamente nelcomponentdidmountmetodo.Questo è il metodo che dovresti usare quando si collega i componenti react.js alle API.

Per prima cosa creeremo unChatManager:

componentDidMount () {const ChatManager = new ChatKit.ChatManager ({Instancelocator: Instancelocator, UserId: UserId, TokenProvider: New Chatkit.TokenProvider ({URL: Testken})}))

... e poi lo faremochatmanager.connect ()Per connettersi con l'API:

chatmanager.connect (). Quindi (currentUser => {CurrentUser.subScriscriceToroom ({RoomID: RoomID, Hooks: {OnNewMessage: Message => {this.setState ({Messages: [... this.state.Messages, Message]}}}})}}})})}

Questo ci dà accesso autente attualeOggetto, che è l'interfaccia per interagire con l'API.

Nota: come dovremo utilizzareutente attualePiù tardi, ben immagazzinalo sull'istanza facendothis.currentUser = `` CurrentUser.

Quindi chiamiamoCurrentUser.SubscriStiscriteToom ()e passalo il nostrostrisciaree unOnnewMessagegancio.

ILOnnewMessageHook viene attivato ogni volta che un nuovo messaggio viene trasmesso nella chat room.Quindi ogni volta che succede, aggiungeremo semplicemente il nuovo messaggio alla fine dithis.state.Messages.

Ciò si traduce nel recupero dei dati dall'API e quindi nel renderli sulla pagina.

Impara a costruire un'app di chat react in 10 minuti - React JS Tutorial (12)

Questo è fantastico, dato che ora abbiamo lo scheletro per la nostra connessione client-server.

Woohoo!

Passaggio 7: gestione dell'input dell'utente

La prossima cosa che dovremo creare è ilSendMessageFormcomponente.Questo sarà un cosiddettocomponente controllato, significa che il componente controlla ciò che viene reso nel campo di input attraverso il suo stato.

Dai un'occhiata alrender ()metodo e presta particolare attenzione alle linee che ho messo in evidenza:

class SendMessageForm estende react.ComPonent {render () {return (   form>)}

Stiamo facendo due cose:

  1. Ascoltando gli input dell'utente con ilOnchangeAscoltatore di eventi, in modo che possiamo
    innescare ilCambia di manometodo
  2. Impostazione delvaloredel campo di input usando esplicitamentethis.state.message

La connessione tra questi due passaggi si trova all'interno delCambia di manometodo.Aggiorna semplicemente lo stato a qualunque cosa l'utente tipi nel campo di input:

HandleChange (e) {this.setState ({Message: e.target.value})}

Ciò innesca un rendering e poiché il campo di input è impostato esplicitamente dallo stato usandovalue = {this.state.message}, il campo di input verrà aggiornato.

Quindi, anche se l'app si sente immediata per l'utente quando digita qualcosa nel campo di input,I dati effettivamente passano tramite lo stato prima che React aggiorni l'interfaccia utente.

Per concludere questa funzione, dobbiamo dare al componente acostruttore.In esso, iniziatizzeremo entrambi lo stato e vinceremoQuestonelCambia di manometodo:

costructor () {super () this.state = {messaggio: ''} this.handlechange = this.handlechange.bind (this)}

Dobbiamo legare ilCambia di manometodo in modo che avremo accesso aQuestoParola chiave al suo interno.È così che funziona JavaScript: ilQuestoLa parola chiave è per impostazione predefinitanon definitoAll'interno del corpo di una funzione.

Passaggio 8: invio di messaggi

NostroSendMessageFormIl componente è quasi finito, ma dobbiamo anche prenderci cura della presentazione del modulo.Dobbiamo recuperare i messaggi e inviarli!

Per fare questo collegheremo aHandlesubmitpersino gestore con ilOnsubmitAscoltatore di eventi nel

.

render () {return (
form>)}

Poiché abbiamo il valore del campo di input memorizzato inthis.state.message, in realtà è abbastanza facile passare i dati corretti insieme alla presentazione.BENE
Basta fare:

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

Qui, stiamo chiamando ilinvia messaggioimpegno e passaggiothis.state.messagecome parametro.Potresti essere un po 'confuso da questo, poiché non abbiamo creato ilinvia messaggiometodo ancora.Tuttavia, lo faremo nella prossima sezione, poiché quel metodo vive all'interno delAppcomponente.Quindi non preoccuparti!

In secondo luogo, stiamo cancellando il campo di input mediante impostazionethis.state.messagea una stringa vuota.

Ecco l'interoSendMessageFormcomponente.Si noti che abbiamo anche legatoQuestoalHandlesubmitmetodo:

Classe SendMessageForm estende react.ComPonent {costructor () {super () this.state = {messaggio: ''} this.HandleChange = this.Handlechange.bind (this) this.handlesubmit = this.handlesubmit.bind (this)} HandleChangeAngeAngeEChange(e) {this.setState ({Message: e.target.value})} HandlesUmmit (e) {e.preventDefault () this.props.sendMessage (this.state.Message) this.setState ({Message: ''})} render () {return (
form>)}}

Passaggio 9: inviare i messaggi a Chatkit

Ora siamo pronti, quindi invia i messaggi a Chatkit.Che è stato fatto nelAppcomponente, dove creeremo un metodo chiamatothis.sendMessage:

SendMessage (text) {this.currentUser.sendMessage ({text: text, roomid: roomid})}

Ci vuole un parametro (il testo) e chiama semplicementethis.currentUser.sendMessage ().

L'ultimo passo è passarlo acomponente come prop:

/ * Componente app * /render () {return (
)}

E con ciò, abbiamo tramanato il gestore in modo cheSendMessageFormpuò invocarlo quando il modulo viene inviato.

Passaggio 10: creazione del componente del titolo

Per finire, creiamo anche il componente del titolo.È solo un semplice componente funzionale, che significa una funzione che restituisce un'espressione JSX.

Titolo funzione () {return 

la mia fantastica app di chat

}

È una buona pratica usare componenti funzionali, in quanto hanno più vincoli rispetto ai componenti di classe, il che li rende meno inclini ai bug.

Il risultato

E con questo in atto hai la tua applicazione di chat che puoi usare per chattare con i tuoi amici!

Impara a costruire un'app di chat react in 10 minuti - React JS Tutorial (13)

Concediti una pacca sul retro se hai codificato fino alla fine.

Se vuoi imparare a costruire ulteriormente su questo esempio,Quindi controlla il mio corso gratuito su come creare un'app di chat con React qui.

Grazie per aver letto e felice programmazione :)

FAQs

How do you make a chat application in Reactjs? ›

Alternatively, you can create your React app by running the code in your terminal, npx create-react-app react-chat , to create it. Here, react-chat is the name of the app. Then you can run npm install firebase react-firebase-hooks to install firebase and react-firebase-hooks.

How do you make a React app in 5 minutes? ›

Steps to Create React Application
  1. Install Create React App. The first step to creating a new React application is to install the Create React App. ...
  2. Start New App. ...
  3. Set Your Libraries. ...
  4. Start Working on Metadata. ...
  5. Set the Images. ...
  6. Set the API. ...
  7. Import the Components. ...
  8. Run the App and Publish.

How do you make a React app for beginners? ›

Building a Simple Task Application
  1. Create the React app on your terminal. On your terminal, run the following command. ...
  2. Start up the React app. ...
  3. Set up component structure. ...
  4. Set up the back end using the Rails API. ...
  5. App component. ...
  6. Nav component. ...
  7. CreateCard component — controlled form. ...
  8. MainComponent — creating a new card.

How do I install React chat engine in React? ›

Add serverless chat to your React app in 3 minutes.
  1. Register then create a project and user at chatengine.io.
  2. Collect the public key, username and user password.
  3. Install yarn add react-chat-engine.
  4. Import the ChatEngine component and pass in publicKey , userName , and userSecret props.
  5. Voila! You're done.

How do you code a chat application? ›

Chat App Development Steps: Process Overview
  1. Create a Directory & Install Dependencies. ...
  2. Build the Front-End Chat Interface & Chat Client. ...
  3. Create and/or Connect the Back End (Chat Server) ...
  4. Prioritize Feature Expansion Based on User Feedback.
Mar 3, 2021

How to create a chat app in JavaScript? ›

You should download them and add them to the img folder inside your project.
  1. Installing JavaScript Dependencies. ...
  2. Remove Existing Users and Groups. ...
  3. Creating a CometChat Chat Widget. ...
  4. Find Your App's Credentials. ...
  5. Configuring CometChat in Your Application. ...
  6. Create a Realtime Database. ...
  7. Add an Authentication Service.

Why does create react app take so long to start? ›

Internet connectivity issues - slow internet or high latency. The terminal used also plays a crucial role. For example, Git Bash is known to have better performance than the Command Prompt on Windows platform.

Can I learn React in 15 days? ›

I learnt React JS in 15 days. On my way, I had to learn JavaScript ES6 and Node JS. I also did a small project for practice. The conclusion I derived from these 15 days is that the fastest way to learn React JS is to practice it in a project.

How do I make React JS app faster? ›

Optimizing performance in a React app
  1. Keeping component state local where necessary.
  2. Memoizing React components to prevent unnecessary re-renders.
  3. Implementing React. ...
  4. Using the useCallback and useMemo Hooks.
  5. Code-splitting in React using dynamic import()
  6. Windowing or list virtualization in React applications.
Feb 9, 2023

Is React hard for beginners? ›

Thankfully, React is easy to learn, but only once you have foundational knowledge in JavaScript. Of course, the difficulty that comes with learning anything new is somewhat subjective. Regardless of your prior experience, plenty of resources are available to help make React easier to learn.

Is React beginner friendly? ›

Small learning curve: React is easy to learn, as it mostly combines basic HTML and JavaScript concepts with some beneficial additions. Still, as is the case with other tools and frameworks, you have to spend some time to get a proper understanding of React's library.

Should I learn React as a beginner? ›

React JS has been an important framework in developers' toolkits for a decade now. But if you're just starting your career, you're probably better off not spending time learning it. Alex Zito is a software developer and technology blogger with experience working in C# and JavaScript.

How do you use react chatbot? ›

Example: To use the chatBot, we need to import it from 'react-simple-chatbot'. For the chatBot to work, we need to create a steps array. The ChatBot takes steps which is an array of objects as its props.

How to create a chat Engine? ›

Let's go to Chat Engine and get your API keys.
  1. Register at chatengine.io.
  2. Click "New Project" and add a project title.
  3. Create your first User, I'll call my user Adam.
  4. Remember the Project ID and the Username + Secret of a user. You will need it later.

How do I install react chatbot kit? ›

Getting Started
  1. Step 1: Install react-chatbot-kit. npm install react-chatbot-kit.
  2. Step 2: Import the dependencies. Import the following dependencies into the app: ...
  3. Step 3: Create the necessary files. The chatbot requires three dependencies in order to function. ...
  4. Step 4: Initialize the chatbot.

How do I create a chatBot for a website in react JS? ›

For the chatBot to work, we need to create a steps array. The ChatBot takes steps which is an array of objects as its props. Although there are a number of options we can pass as props to our chatBot without the steps props it will show a blank screen.

How do I create a chat app in react JS and Firebase? ›

Set Up the Firebase Project and the React Client
  1. After creating your project, select and click on the code icon on the project's overview page to register your application. ...
  2. Take note of the instructions for integrating Firebase's SDK to your project under Add Firebase SDK. ...
  3. Define the database mode and location.
Feb 17, 2023

How do I make a social media app with Reactjs? ›

How to build a social media app with React
  1. Set up your development environment: Install Node. ...
  2. Create a new React project: ...
  3. Design the application architecture: ...
  4. Implement the UI components: ...
  5. Manage status: ...
  6. Implement routing: ...
  7. Integrate back-end functionality: ...
  8. Implement user authentication:
May 17, 2023

How do you make a chat app like discord? ›

How to make an app like Discord for free?
  1. Visit the Appsgeyer website.
  2. Click on the Messenger App template.
  3. Choose your color theme. ...
  4. Select a suitable background image.
  5. Give your app a name.
  6. Select a customizable icon.
  7. Publish your Android app on Google Play and start earning money today.
May 26, 2023

Top Articles
Latest Posts
Article information

Author: Ms. Lucile Johns

Last Updated: 13/11/2023

Views: 5984

Rating: 4 / 5 (41 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Ms. Lucile Johns

Birthday: 1999-11-16

Address: Suite 237 56046 Walsh Coves, West Enid, VT 46557

Phone: +59115435987187

Job: Education Supervisor

Hobby: Genealogy, Stone skipping, Skydiving, Nordic skating, Couponing, Coloring, Gardening

Introduction: My name is Ms. Lucile Johns, I am a successful, friendly, friendly, homely, adventurous, handsome, delightful person who loves writing and wants to share my knowledge and understanding with you.