0

We can use function component inside a class component, is it possible to do the other way around? For example

class MyClassComponent extends React.Component {
    render() {
        return (
            <p>This is a class component with display {this.props.display}</p>
        )
    }
}
const MyFunctionComponent = (props) => {
    return <MyClassComponent display=props.shouldDisplay>This is a function component</MyClassComponent >
}
0

1 Answer 1

3

React makes it transparent for you whether the components you use are functions or classes, so you can compose them as you like.

Specifically in your code there are two issues that you might want to reconsider:

  1. When you define a prop, its value should be wrapped in curly brackets:
<MyClassComponent display={props.shouldDisplay}>
  1. Components can be either self-closing or have children props. In your case, you've added text inside the opening tag and the closing tag, which you can access in MyClassComponent via this.props.children:
const ChildComponent = (props) => {
    return (
        <div>
            {this.props.children}
        </div>
    );
}

const ParentComponent = (props) => {
    return (
        <ChildComponent>
            Hello World
        </ChildComponent>
    );
}

const App = (props) => {
    return <ParentComponent/>;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.