Abdul Hanan Asif
Abdul Hanan Asif

Reputation: 97

State is getting input from user but not displaying on webpage in React.js

Actually i'm building a Facebook Mesenger Clone in React.js and I used material UI. When we run the code it asks for username. after providing that we can send message in the app. But as soon as we send the message we only get username printed on the screen as can be seen in screenshot. The message is not being displayed on the webpage. This is App.js code:


    import React, {useEffect, useState} from 'react';
import {Button, FormControl, Input, InputLabel} from "@material-ui/core";
import Message from "./Message";
import './App.css';

function App() {

    const [input, setInput] = useState('');
    const [messages, setMessages] = useState([]);
    const [username, setUsername] = useState('');

    useEffect(() => {
        setUsername(prompt('Please enter your name'));
    }, [])

    const sendMessage = (event) => {
        event.preventDefault();
        setMessages([...messages, {username: username, text: input}]);
        setInput('');
    }

    return <div className="App">

        <h1>Hey Mate! 😃</h1>
        <h2>Welcome {username}</h2>
        <form>
            <FormControl>
                <InputLabel>Enter a message...</InputLabel>
                <Input value={input} onChange={event => setInput(event.target.value)}/>
                <Button disabled={!input} variant="contained" color="primary" type='submit' onClick={sendMessage}>Send
                    Message</Button>
            </FormControl>
        </form>


        {
            messages.map(message => <Message username={username} message={message}/>)
        }

    </div>
}

export default App;

and this is message component's code:

      import React from "react";
import {Card, CardContent, Typography} from "@material-ui/core";
import './Mesage.css';

function Message(message, username) {

    const isUser = username === message.username;

    return (
        <div className={`message ${isUser && 'message_user'}`}>
            <Card className={isUser ? "message_userCard" : "message_guestCard"}>
                <CardContent>
                    <Typography color="white" variant="h5" component="h2">
                        {message.username}: {message.text}
                    </Typography>
                </CardContent>
            </Card>
        </div>

    )
}

export default Message;

Kindly help me

Upvotes: 1

Views: 52

Answers (1)

Pavel Alekseev
Pavel Alekseev

Reputation: 1222

You are getting props in the Message component wrong. Just change it to

function Message({ message, username }) {
  ...
}

Upvotes: 2

Related Questions