InterviewSolution
| 1. |
What are props in React? |
|
Answer» Props or properties are REACT way to pass data from parent component to child component. Props can be passed to both Function based component or CLASS-based components. Consider this React CODE for About Page. import React from ‘react’; import Header from ‘./HeaderPage’; import Footer from ‘./FooterPage’; const AboutPage =() => { return( <div> <Header text=“Hero Company” subText=“Cool Company” /> <h1>About Us</h1> <p>We are a cool web development company, located in SILICON Valley.</p> <Footer /> </div> ) }; export default AboutPage;Now the code for Header. import React from ‘react’; const Header =() => { return( <div> <h1>{props.text}</h1> <h2>{props.subText}</h2> </div> ) };export default Header; In the above, we pass two props text and subText from Parent Component AboutPage to Child Component Header. We access the props in Child Component by the keyword props dot and the PROP name. Notice, that we used the {} because props.text is a JavaScript statement and that is how we access JavaScript inside React. There is a slightly different way to access props in class-based components. Here we access props in child components by this.props. Changing our Header Component to class-based component. Consider this React code for About Page. import React from ‘react’; import Header from ‘./HeaderPage’; import Footer from ‘./FooterPage’; const AboutPage =() => { return( <div> <Header text=“Hero Company” subText=“Cool Company” /> <h1>About Us</h1> <p>We are a cool web development company, located in Silicon Valley.</p> <Footer /> </div> ) }; export default AboutPage;Now the code for Header. import React, { Component } from ‘react’; class Header extends Component { render() { return( <div> <h1>{this.props.text}</h1> <h2>{this.props.subText}</h2> </div> ) } export default Header; |
|