Skip to main content

Props

Les Props

Les props (propriétés) sont les paramètres passés à un composant depuis son parent. Elles sont en lecture seule — un composant ne doit jamais modifier ses propres props.

Passage de props

// Parent
<Profil nom="Hugo" age={25} admin={true} />

// Enfant
function Profil({ nom, age, admin }) {
  return (
    <div>
      <p>{nom}, {age} ans {admin && "👑"}</p>
    </div>
  );
}

Valeurs par défaut

function Bouton({ label = "Cliquer", variant = "primary" }) {
  return <button className={variant}>{label}</button>;
}

Spread de props

const props = { nom: "Hugo", age: 25 };
<Profil {...props} />

La prop children

function Panel({ title, children }) {
  return (
    <section>
      <h3>{title}</h3>
      {children}
    </section>
  );
}

<Panel title="Info">
  <p>Texte dans le panel</p>
</Panel>

PropTypes (validation)

import PropTypes from 'prop-types';

Profil.propTypes = {
  nom: PropTypes.string.isRequired,
  age: PropTypes.number,
  admin: PropTypes.bool,
};

Profil.defaultProps = {
  age: 0,
  admin: false,
};