DEV Community

Kiruthiga S
Kiruthiga S

Posted on

React JS

Props
Props are used to pass data from a parent component to a child component

function Parent(props) {
  return <h1>Hello, {props.name}!</h1>;
}
function Child() {
  return <Parent name="John" />;
}
Enter fullscreen mode Exit fullscreen mode

Destructuring props

function Greeting({ name, age }) {
  return (
    <div>
      <h1>Hello,I'm {name}!</h1>
      <p>I am {age} years old.</p>
    </div>
  );
}

function App() {
  return <Greeting name="Kiruthiga" age={21} />;
}
Enter fullscreen mode Exit fullscreen mode

What are the ways to use props

  1. Passing Strings
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

function App() {
  return <Welcome name="Alice" />;
}
Enter fullscreen mode Exit fullscreen mode
  1. Passing Numbers
function Student({ marks }) {
  return <p>Marks: {marks}</p>;
}

function App() {
  return <Student marks={95} />;
}
Enter fullscreen mode Exit fullscreen mode
  1. Passing Boolean Values
function User({ isLoggedIn }) {
  return (
    <h1>{isLoggedIn ? "Welcome!" : "Please Login"}</h1>
  );
}

function App() {
  return <User isLoggedIn={true} />;
}
Enter fullscreen mode Exit fullscreen mode
  1. Passing Arrays
function Fruits({ items }) {
  return (
    <ul>
      {items.map((fruit) => (
        <li key={fruit}>{fruit}</li>
      ))}
    </ul>
  );
}

function App() {
  return <Fruits items={["Apple", "Banana", "Orange"]} />;
}
Enter fullscreen mode Exit fullscreen mode
  1. Passing Objects
function Employee({ emp }) {
  return (
    <div>
      <h2>{emp.name}</h2>
      <p>{emp.role}</p>
    </div>
  );
}

function App() {
  const employee = {
    name: "John",
    role: "Developer",
  };

  return <Employee emp={employee} />;
}
Enter fullscreen mode Exit fullscreen mode
  1. Passing Functions
function Button({ handleClick }) {
  return <button onClick={handleClick}>Click Me</button>;
}

function App() {
  function greet() {
    alert("Hello!");
  }

  return <Button handleClick={greet} />;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)