Home > Net >  ReactJS if statement or conditionals inside jsx file
ReactJS if statement or conditionals inside jsx file

Time:04-15

i have the app putting names up of made up people. I want to see if i can add a conditional or if statement to my mapping in Name.jsx. If so, how would i do that? If anyone can help me this, that would be great! I would want it to pull firstName and lastName if lastName is a specific name.

codesandbox

App.js

import "./styles.css";
import Name from "./Name";

const PEOPLE = [
  {
    firstName: "noah",
    lastName: "reyes"
  },

  {
    firstName: "elissa",
    lastName: "reyes"
  },

  {
    firstName: "ryan",
    lastName: "fink"
  },

  {
    firstName: "alea",
    lastName: "black"
  },

  {
    firstName: "alyssa",
    lastName: "black"
  },

  {
    firstName: "charmaine",
    lastName: "long"
  },

  {
    firstName: "emma",
    lastName: "johnson"
  },

  {
    firstName: "bill",
    lastName: "johnson"
  },

  {
    firstName: "elouise",
    lastName: "morgan"
  }
];

export default function App() {
  return (
    <div className="App">
      <Name list={PEOPLE} />
    </div>
  );
}



**Name.jsx**

export const Name = (props) => {
  const { list } = props;
   
  return (
    <header>
      {list.map((item) => (
        <div className="peoplelist">
          <>
            {item.firstName} : {item.lastName}
          </>
        </div>
      ))}
    </header>
  );
};

export default Name;

CodePudding user response:

list
  .filter(({lastName}) => lastName === 'long')
  .map(item => <>{item.lastName}</>)

will output only items having long lastName. .map method returns array of the same length as source array.

  • Related