mani_ninja
mani_ninja

Reputation: 123

React Custom component not getting rendered

*Custom component is not getting render on UI, also note that I have element by id: root

function CComponent(prop) {
  const element = (
    <div className="container">
      <div className={prop.classname}>{prop.content}</div>
    </div>
  );

  return element;
}

const helloElement = (
  <CComponent>{{ classname: "xyz", content: "helloWorld" }}</CComponent>
);

console.log(helloElement);
ReactDOM.render(helloElement, document.getElementById("root"));

Upvotes: 1

Views: 53

Answers (4)

uke
uke

Reputation: 891

With babel 7 and react >= 16 it wont work. CComponent gets a children prop with {classname,content} object.

You can try change the syntax a bit and it will render perfectly to

<CComponent {...{ className: "xyz", content: "helloWorld" }} />

Upvotes: 0

mani_ninja
mani_ninja

Reputation: 123

According to react doc :

React.createElement(
   type,
   [props],
   [...children]
)

<CComponent>{{ classname: "xyz", content: "helloWorld" }}</CComponent> this was compiled by babel to :

var helloElement = React.createElement(CComponent, null, {
  classname: 'xyz',
  content: 'helloWorld'
})

But <CComponent classname='xyz' content='helloWorld' />

got compiled to

var helloElement= React.createElement(CComponent, {
  classname: "xyz",
  content: "helloWorld"
})  

Hence was rendered on UI

Upvotes: 0

kazmi066
kazmi066

Reputation: 625

You are passing your values as children, to pass values as props, you do this:
<CComponent classname='xyz' content='helloWorld' />

Upvotes: 1

Sam R.
Sam R.

Reputation: 16450

You need to pass props to component like this:

const helloElement = <CComponent classname='xyz' content='helloWorld' />

Upvotes: 1

Related Questions