简体   繁体   中英

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如屏幕截图所示 . 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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM