Tuesday, February 16, 2021

React Props

Props are an optional input, and can be used to send data to the component. Props are a way of making components easily and dynamically customizable. It’s important to note that props are read-only and that a component must never modify the props passed to it. This also makes them come in handy when you want to display fixed values.

Now that you know about props, make use of them in the components that we have just created with a custom name appended to it.

Make changes to the code between the script tags in your App.js  document to make it look like this:

import MyComponent1 from "./MyComponent1";
import MyComponent2 from "./MyComponent2";

function App() {
  return (
    <div className="App">
      <MyComponent1 name="Beta-Labs" />
      <MyComponent2 name="Beta-Labs" />
    </div>
  );
}
export default App;


This renders the text “Beta-Labs” to the screen. Go ahead and play around with this by switching out the name for yours. Using props added some new syntax to your app.

 

Using Props with Function Components

1.    An argument (props) is passed to the functional component. Recall that since a single argument is being passed to function. Passing this argument lets the component know to expect some data to be passed to it.

2. Within MyComponent1.jsx, the name you want rendered to the screen is passed in by specifying {props.propValue} within the component’s tag.

3.    In the h3 tag, {} are used to print the name that is added to the props object when it’s passed in via the component’s tag. Notice that the name attribute is accessed using the dot syntax.


There is no limit to how many props can be supplied to a component. Now Make changes to the code of MyComponent1.jsx to pass props to the class component:


MyComponent1.js

 

import React from "react";
function MyComponent1(props) {
  return (
    <div>
      <h1>This is Function Component </h1>
      <h3>created by: {props.name}</h3>
    </div>
  );
}
export default MyComponent1;

 

Using Props with Class Components

Adding props to class components is a very similar process to the one used in the functional component above. There are three notable changes:

1.    Props is not passed as an argument to the class

2.    The name attribute is accessed using this.props.name instead of props.name

3.  To pass props to the class component, We just define the normal constructor function (which receives a props object) and call the super method to honour the inheritance of the component.

Now Make changes to the code of MyComponent2.jsx to pass props to the class component:


MyComponent2.js

import React from "react";

class MyComponent2 extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div>
        <h1>This is Class Component </h1>
        <h3>created By: {this.props.name}</h3>
      </div>
    );
  }
}
export default MyComponent2;