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?
Using JSX, you can create a function and return a set of JSX elements to a variable, and that variable used is to render the elements inside the render() function in React.
cloneElement() method used here. This method is used to create the clone of the element that will be given as an argument, also here we can pass props and children as arguments. Here variable “c” is passed as an element in React. cloneElement() method for cloning, also passed props {name1: “C++”, name2: “JAVA”}.
To pass props, add them to the JSX, just like you would with HTML attributes. To read props, use the function Avatar({ person, size }) destructuring syntax.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With