11. Component Props

Props stands for properties.

Props are arguments passed into React Components. 

Props are passed to components via HTML elements.


 

React props are like function arguments in javascript and javascript attributes.

To send props into a component, use the same syntax as HTML elements.

So We will be setting up key value pair for our <Header /> Component.

 
    <Header title="Component Props" />
    console.log(this.props);

 

    class Header extends React.Component {
        render() {
        return (
            <div>
            <p>{this.props.title}</p>
            </div>
        );
        }
    }

    const jsx = (<div>
        <Header title="Component Props" />
    </div>);

    ReactDOM.render(jsx, document.getElementById('app'));



We can pass title dynamically as well .

  
const title = "Component Props";
    const jsx = (<div>
        <Header title={title} />
    </div>);


lets do simple challange here.

//Setup options prop for options component.

//Render the length of an array.

    
 class HelloApp extends React.Component {
      render() {
        const title = 'Hello';
        const subtitle = 'How are you?';
        const option = ['Thing one', 'Thing two', 'Thing four'];

        return (
          <div>
            <Header title={title} subtitle={subtitle} />
            <Option options={option} />
          </div>
        );
      }
    }

    class Header extends React.Component {
      render() {
        return (
          <div>
            <h1>{this.props.title}</h1>
            <h2>{this.props.subtitle}</h2>
          </div>
        );
      }
    }

    class Option extends React.Component {
      render() {
        return (
          <div>
          <p>Option array: {this.props.option}</p>
          <h2>Option array Length: {this.props.option.length}</h2>
          </div>
        );
      }
    }

    ReactDOM.render(<HelloApp />, document.getElementById('app'));


 All our properties will be available on {this.props}.


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Comments