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
This does not work because the single
<span>
will be returned on the first iteration. Instead, tryEssentially, 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:This is because of the
return
statement inside thefor
loop.an alternative is to make the
fullName
function returning an array ofspan
from theannie
object using Object.values(), then this can be displayed within the JSX :