Chris
Chris

Reputation: 31196

React/JS: how to pass html element via function?

Suppose I have:

const list_item = (key,str) => <li key={key}>{str}</li>

and, in my render func,

<li key={mykey}> {mystring} <MdCheckCircle /> </li>

When I place the list_item function in the render method, however, I cannot add <MdCheckCircle/>:

list_item(mykey,mystring + "<MdCheckCircle/>")
// renders as string literal on the site

list_item(mykey,mystring + <MdCheckCircle/>) 
// renders as "[ Object ]" on the site

How do I pass this html element such that it renders properly?

Upvotes: 0

Views: 1995

Answers (1)

Birbal Singh
Birbal Singh

Reputation: 1072

You can pass component direct into function like as another parameter

const list_item = (key, str, comp) => <li key={key}>{str} {comp}</li>;

const MdCheckCircle = () => <div>Circle</div>;

class App extends Component {
    render() {
        return <div>{list_item(1, "string", <MdCheckCircle />)}</div>;
    }
}

Upvotes: 4

Related Questions