skip to Main Content

Here’s a condensed version of my code. I think you can get what I’m trying to do, but only the first name displays. Can anyone show me the proper way to do this in React?

  import "./styles.css";
  import { useState } from "react"; 



  export default function App() {
  const [annie, renameAnnie] = useState({
    firstname: "Annie",
    middlename: "Rose",
    lastname: "Markham"
  });

  const fullName = () => {
    for (let x in annie) {
      return(
     <span>{annie[x]}</span>
      )
    }
  };


  return (
    <>
      {fullName()}
    </>
  );
}

2

Answers


  1. This does not work because the single <span> will be returned on the first iteration. Instead, try

        return (
            <>
                {Object.values(annie).map((item, index) => (
                    <span key={index}>{item}</span>
                ))}
            </>
        )
    

    Essentially, using Array.prototype.map() we can construct a new array where each element is yielded by a function on the values of annie. You can think of it as a more concise way to write the following:

    const results = []
    const values = Object.values(annie)
    for (let i = 0; i < values.length; i++) {
        results.append(<span key={i}>{values[i]}</span>)
    }
    return <>{results}</>
    
    Login or Signup to reply.
  2. but only the first name displays

    This is because of the return statement inside the for loop.

    an alternative is to make the fullName function returning an array of span from the annie object using Object.values(), then this can be displayed within the JSX :

    const fullName = () => {
        return Object.values(annie).map((value, index) => (
          <span key={index}>{value}</span>
        ));
      };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search