5

Suppose I already define an component:

class Co extends React.Component {
    render = () => {
        const name = this.props.name;
        return (
            <p>Hello, my name is {name}</p>
        )
    }
}

and store it in an variable:

const co = <Co />;

How can I set the component's props with the variable? Would co.props.set work?

2 Answers 2

6

As I understand you don't want to render your component in JSX syntax but with your stored variable. You can have a look at React.cloneElement. This should do what you want:

{React.cloneElement(co, {name: 'hans'})}

See: https://facebook.github.io/react/docs/top-level-api.html#react.cloneelement

Sign up to request clarification or add additional context in comments.

Comments

0

You can set props as usual

<Co name="Name"/>

If element is child of some component then you can use React.cloneElement()

class Parent extends React.Component {
    render = () => {
        const name = this.props.name;
        return (
            <SomeComp><Co/></SomeComp>
        )
    }
}
class SomeComp extends React.Component {
    render = () => {
        const name = this.props.name;
        return (
            <SomeComp>{React.cloneElement(this.props.children, {name:"Name"})}</SomeComp>
        )
    }
}

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.