kkkk
kkkk

Reputation: 329

Is there a way of passing props to class component?

I'm a beginner in React.
I still quite don't understand how to pass props to a class component like we do in a function.
Example of a function:

const SurveyFormReview = ({ onCancel, formValues, submitSurvey, history }) => {
    return (
        ...
        <button
            onClick={() => submitSurvey(formValues, history)}
            className="green btn-flat right white-text"
        >
        ...
    );
};

Example of a class Component:

class ImageUpload extends Component {
    render() {
        return (
            // I want to use props in here
        )
    }
}

Upvotes: 2

Views: 1688

Answers (3)

msvan
msvan

Reputation: 39

For example

<ImageUpload propExample="property" />

Inside ImageUpload component you can access it by writing:

this.props.propExample

Upvotes: 2

Asif vora
Asif vora

Reputation: 3359

You can pass any value as a props in Class and functional components in react. Read more about props

class Welcome extends React.Component {
    render() {
        return <h1>Hello, {this.props.name}</h1>;
    }
};

ReactDOM.render(
    <Welcome name="Sara" />,
    document.getElementById('root')
);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
    <div id="root"></div>

Upvotes: 1

Michael Lucero
Michael Lucero

Reputation: 36

Just use whatever attributes you want when using the ImageUpload component:

<ImageUpload propA="someValue" propB={someVariable}/>

From the ImageUpload component, just call the props property:

someFunction = () => {
    var propAValue = this.props.propA;
    var propBValue = this.props.propB;
}

That's it!

Upvotes: 2

Related Questions