Search code examples
reactjsreact-componenttsx

React Component access Props


Is it possible to access the inner property of a React Component?

Examples of React Component usually show prop types as HTML/XML inner properties:

<MyComp paramOne='val1' paramTwo='val2' />

The class for that would be:

import * as React from 'react';

export interface MyCompProps {
    paramOne: string;
    paramTwo: string;
}

export interface MyCompState {

}

export class MyComp extends React.Component<MyCompProps, MyCompState> {
    public render() {
        return <div>
            <ul>
                <li>paramOne: {this.props.paramOne}</li>
                <li>paramTwo: {this.props.paramTwo}</li>
            </ul>
        </div>;
    }
}

Is it though possible to access val3 in the following example code?

<MyComp paramOne='val1' paramTwo='val2'>val3</MyComp>

Solution

  • Your val3 would be accessible via the children prop.

    export class MyComp extends React.Component<MyCompProps, MyCompState> {
        public render() {
            return <div>
                <ul>
                    <li>paramOne: {this.props.paramOne}</li>
                    <li>paramTwo: {this.props.paramTwo}</li>
                    <li>children: {this.props.children}</li>
                </ul>
            </div>;
        }
    }
    
    <MyComp paramOne='val1' paramTwo='val2'>val3</MyComp>