skip to Main Content

I’m having difficulty understanding the difference between attributes and props in React. Can you please provide a clear explanation with examples? I’ve already tried searching, but it hasn’t helped me understand.

i have tried to read different but not unserstand clearly

2

Answers


  1. props is an object containing the attributes defined when using the component.

    // props contains hours/minutes/seconds when component is defined
    const Clock = (props) => {
      return (
        <div>${props.hours}:${props.minutes}:${props.seconds}</div>
      );
    };
    
    const App = () => {
      // and here the hours/minutes/seconds are defined, as attributes
      // when component is instantiated
      return (
        <Clock hours="15" minutes="43" seconds="29" />
      );
    };
    

    Since it’s quite verbose to write props.attribute for all attributes, props is usually de-structured, e.g.

    const Clock = ({ hours, minutes, seconds }) => {
      return (
        <div>${hours}:${minutes}:${seconds}</div>
      );
    };
    
    Login or Signup to reply.
  2. They are very similar, but an attribute is a "property" with a pre-defined "key" that you set on a native element, while a "prop" is a "property" that you set on a custom element (react functional or class component).

    So, for example, if you have <img src='foo.png'/> then src is an attribute of the resulting DOM node.

    But if you have <MyComponent src='foo.png'/> then src is a prop, which is passed to the custom component in its ‘props’.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search