0%
Props and State in React

Props and State

Data management

10-15 min

Props and State in React

Props and state are two fundamental React concepts for managing data. They make components dynamic and interactive.

Props

Props (short for properties) are a way to pass data from a parent component to a child component. They are read-only and cannot be modified by the child component.

Using props

// Composant enfant
function UserCard({ name, age, email }) {
  return (
    <div className="user-card">
      <h2>{name}</h2>
      <p>Âge : {age}</p>
      <p>Email : {email}</p>
    </div>
  );
}

// Composant parent
function App() {
  return (
    <div className="app">
      <UserCard
        name="Marie Dupont"
        age={25}
        email="marie@example.com"
      />
    </div>
  );
}

Default props

You can define default values for props:

function Button({ text = "Cliquez-moi", onClick }) {
  return <button onClick={onClick}>{text}</button>;
}

Props.children

The special children prop lets you pass content between a component's tags:

function Card({ children }) {
  return <div className="card">{children}</div>;
}

// Utilisation
<Card>
  <h2>Titre</h2>
  <p>Contenu</p>
</Card>

Comments

Comments are powered by GitHub Discussions

Sign in with GitHub to join the discussion

Link copied!