React Props


Props of arguments have been transferred to React components.

Props are transmitted in sections with HTML attributes.


Props represent properties.



React Props

React Props is similar to the JavaScript functionality and attributes in HTML.

To post props in section, use the same syntax as HTML attributes:


Example

Add a "brand" attribute to the Car element:

const myelement = <Car brand="Ford" />;

The component receives an argument as a props:


Example

Use the brand attribute in the component:

function Car(props) {
            return <h2>I am a { props.brand }!</h2>;
          }
          


Pass Data

Props are a method of transferring data from one component to another, such as parameters.


Example

Send the "brand" property from the Garage component to the Car component:

function Car(props) {
            return <h2>I am a { props.brand }!</h2>;
          }
          
          function Garage() {
            return (
              <>
                <h1>Who lives in my garage?</h1>
                <Car brand="Ford" />
              </>
            );
          }
          
ReactDOM.render(<Garage />, document.getElementById('root'));
          

If you have a variable to send, and not a character unit as in the example above, simply enter the variable word inside the curved brackets:


Example

Create a variable named carName and send it to the Car component:

function Car(props) {
            return <h2>I am a { props.brand }!</h2>;
          }
          
          function Garage() {
            const carName = "Ford";
            return (
              <>
                <h1>Who lives in my garage?</h1>
                <Car brand={ carName } />
              </>
            );
          }
          
ReactDOM.render(<Garage />, document.getElementById('root'));
          

Or if it was:


Example

Create an object named carInfo and send it to the Car component:

function Car(props) {
            return <h2>I am a { props.brand.model }!</h2>;
          }
          
          function Garage() {
            const carInfo = { name: "Ford", model: "Mustang" };
            return (
              <>
                <h1>Who lives in my garage?</h1>
                <Car brand={ carInfo } />
              </>
            );
          }
          
ReactDOM.render(<Garage />, document.getElementById('root'));
          

Note: React Props is readable only! You will get an error if you try to change their value.