0

I am reading a book "Pure React" by Dave Ceddia, below is a question I am getting stuck, I appreciate for any solution as simple as possible, thanks.

Question: Return the appropriate JSX from this component so that when username is undefined or null, it renders “Not logged in”. When username is a string, render “Hello, username

My answer:

import React from 'react';
import ReactDOM, { render } from 'react-dom';

function Greeting(){
  render(){
   let username = '';
   let greeting = '';

   if(typeof username == String){
    greeting = <span>Hello {username}</span>
   }else{
    greeting = <span>Not logged in</span>;
   }

   return (
    <div>
     <input type="text" value={username}/>
     {greeting}
    </div>
   )
  }
 }

ReactDOM.render(
  <Greeting/>,
  document.getElementById('root')
);
1
  • What's your problem?
    – GalAbra
    Commented Aug 8, 2020 at 9:14

4 Answers 4

0

You mixed class component syntax with functional component syntax.

Below I rewrite your code to correct functional component using React Hooks. Also, I use inline If-Else conditional rendering greeting element.

const { useState } = React;

function Greeting(){
  const [username, setUsername] = useState("");
   
  let greeting = username 
    ? <span>Hello {username}</span>
    : <span>Not logged in</span>;
     
  return (
    <div>
     <input type="text" value={username} onChange={(e) => setUsername(e.target.value)} />
     {greeting}
    </div>
  )
}

ReactDOM.render(
  <Greeting/>,
  document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>

0

You can define state such as username and make your greeting message dependent upon it on change. I have created following sandbox to show the solution:

https://codesandbox.io/s/unruffled-browser-iohyt

Following is the component's JS code:

import React from "react";

export default function Greeting() {
  const [ username, setUserName ] = React.useState(null);

  return (
    <div>
      <input
        type="text"
        value={username}
        onChange={evt => setUserName(evt.target.value)}
      />
      <span>{username ? `Hello ${username}`:"Not logged in"}</span>
    </div>
  );
}
0

Three things:

  • username is your component input, so you must pass it as prop. You could set a default value to it in the case this is not defined. Although you might have presented above for demonstration/test purposes
  • Your component is not a class from the look of what you shared, this a functional component. Therefore, render class method doesn't apply here
  • The question says "when username is undefined or null, it renders “Not logged in”", you should just follow what the question is saying by not reversing the logic on checking if username is a string
import React from 'react';
import ReactDOM, { render } from 'react-dom';

function Greeting({ username = '' }) {
   let greeting;
   if (username === undefined || username === null) {
      greeting = (<span>Not logged in</span>);
   } else {
      greeting = (<span>Hello {username}</span>);
   }

   return (
    <div>
     <input type="text" value={username}/>
     {greeting}
    </div>
   )
  }
 }

ReactDOM.render(
  <Greeting username='' />,
  document.getElementById('root')
);

4
  • Hi your answer is the most simple one which is what I want, because I am not familiar with React syntax yet. However, I got 'greeting' is not defined no-undef, could you please check how to correct it? Thanks
    – Jeff Lung
    Commented Aug 8, 2020 at 9:43
  • Thanks, but I cannot type any word in the input field, please check,thanks.
    – Jeff Lung
    Commented Aug 8, 2020 at 9:59
  • You need to pass a callback to the input element in order to mutate your state and control your component, please read react doc Commented Aug 8, 2020 at 10:09
  • You are welcome! React hooks are rough to learn but I believe the new paradigm will make things easier to move with! Commented Aug 8, 2020 at 23:57
0
    function Header() {
        let username = 'Username_here';
        let isValid;
        function validString(){
            if(typeof username === 'string'){
            return isValid=true;
            }
            else {
                return isValid=false;
            }
        }
        validString();
    
        return (
            <>
            <span>
                {isValid && 'Hello,' +  username}
                {!isValid && 'Not Logged In'}
            </span>
            </>
        );
    }
    
    export default Header;

At first I created a component header then just import this to app.js file.
1
  • While this code snippet may solve the problem, it doesn't explain why or how it answers the question. Please include an explanation for your code, as that really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Commented Jan 27, 2022 at 16:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.