Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React js: How to set props in JSX components which store in variable

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?

like image 719
hh54188 Avatar asked Jul 01 '16 12:07

hh54188


People also ask

Can I store JSX in variable?

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.

How do you pass props to Reactjs component that wrapped in variable?

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”}.

How do I pass JSX in props?

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.


1 Answers

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

like image 101
Richard Rutsche Avatar answered Sep 23 '22 04:09

Richard Rutsche