React - Props
As discussed at high level in my previous article, state and props are models in react which holds information. A state can be local to a component which can be shared with its subsequent children in the form of props. props is a pre-populated object in react which is passed to every component (class or functional) and holds data and methods shared by the caller component.
Lets look at props in detail.
React Props
- They are the custom properties or attributes of the JSX/react/html element
- Props include data that we give it to a component, which it might need to perform some operation
- Components can’t change or assign values to the props attributes, as props are immutable objects similar to constants. Doing so will throw an error! We can still change properties of objects unlike object itself.
- this.props.fname = "Hardik"; // this throws error!this.props.name.fname = "Hardik"; //this works!
- By using props, components in a tree can communicate with each other by sharing data, calling functions exposed by others.
- Steps
- Set the custom properties at the caller element
- Call/render the component with props parameter
- Pass individual properties or inline objects using {{}} or objects directly
- Functions can also be passed as props to children
- Props to the called component is a function parameter so can be called anything but as per recommendation its suggested to use props.
- In the called component, they can be destructured to pick and choose the properties needed by that component
- Below example will demonstrate how props can be passed from parent to children
- //Children 1class BookImage extends React.Component {render() {//notice how props object is automatically//populated with set value from parent in this.props.coverImageconst coverImage = this.props.coverImage;//using prop as a valuereturn <img src={coverImage} alt="Book Cover"></img>;}}//children 2class BookAuthor extends React.Component {render() {//you can console.log props too!console.log("props", this.props);//props paired with object destructuringconst { title, author } = this.props;return (<><h2>{title}</h2><h4>{author}</h4><p>{this.props.description}</p>{/* Notice how event exposed by parent for buying the book is tagged! */}{/* On button click, parent method is fired! */}<button onClick={this.props.buyBook}>Buy this Book!</button></>);}}//Parent componentclass Book extends React.Component {render() {const title = {title: "The Alchemist",};const writer = {author: "Paulo Coelho",};const description = {description: "Lorem, ipsum dolor sit amet adipisicing.",};//method to buy the book, to be passed to childrens who needs itconst buyBook = () => {alert("Bought it!");};return (<>{/* setting prop: way 1 => setting the required property directly */}<BookImage coverImage="./image/the-alchemist.jpg" /><BookAuthor{...writer} //setting prop: way 2 => leveraging object destructuringprops={title} // setting prop: way 3 => setting the object directly//setting prop: way 4 => setting the required property from object directlydescription={description.description}buyBook={buyBook} //setting prop way 5: => exposing the function for children to execute!/></>);}}ReactDOM.render(<Book />, document.getElementById("container"));
- Props gets passed from parent to the child in the form of either a property, object or function.
- Props object is populated automatically by react thanks to its declarative syntax.
- Lets discuss in detail how props from parent (Book) can be passed to the child components (BookImage, BookAuthor) in the example above.
- Assigning the required property directly with a value, ex., coverImage
- Leveraging object destructuring, ex., writer
- Setting up the objects directly, ex., title
- Setting up the required property directly from an object, ex., description.description
- Exposing function of parent to children for execution, ex., buyBook
Children Prop
- Sometimes, some child components will have children which not necessarily others will have.
- For example, not all books will have publisher's name for displaying book. Parent might send it for selective books where it has that data.
- To take care of such situations, we can leverage props.children property, which will treat such optional values/elements as children itself.
- While passing children, make sure that the element or value is between the opening and closing value of the component.
- Example:
- //Children 1class BookImage extends React.Component {render() {const coverImage = this.props.coverImage;return <img src={coverImage} alt="Book Cover"></img>;}}//children 2class BookAuthor extends React.Component {render() {console.log("props", this.props);const { title, author } = this.props;return (<><h2>{title}</h2><h4>{author}</h4><p>{this.props.description}</p>{/* render using children keyword, automatically populated */}{this.props.children}<button onClick={this.props.buyBook}>Buy this Book!</button></>);}}//Parent componentclass Book extends React.Component {render() {const title = {title: "The Alchemist",};const writer = {author: "Paulo Coelho",};const description = {description: "Lorem, ipsum dolor sit amet adipisicing.",};const buyBook = () => {alert("Bought it!");};return (<><BookImage coverImage="./image/the-alchemist.jpg" /><BookAuthor{...writer}props={title}description={description.description}buyBook={buyBook}> {/* <<== notice that the self closing tag is not used!*/}{/* Child element is sitting inside the BookAuthor element */}<p>Lorem ipsum dolor sit amet consectetur adipisicing elit.Repellendus, natus voluptate. Dolores esse placeat eveniet quod velaccusamus mollitia amet.</p>{/* Closing the BookAuthor tag */}</BookAuthor></>);}}ReactDOM.render(<Book />, document.getElementById("container"));
State vs Props
- Props include data that we give it to a component.
- State includes data which is local/private to the component, other components cant access that state directly.
- Props are immutable but state can be changed within the component.
- Both props and state can issue re-render of the UI.
Comments
Post a Comment