Sunday, March 25, 2018

[React.js][Resolved] Passing class name to render function in react component


Example code:
var Article = React.createClass({
  render:function(){
    return (
      <article>
        <h2>Title</h2>
        <p>content</p>
        <div class="meta">Last updated by author at 23-11-2018 12:45:30</div>
      </article>
    );
  }
});

This segment of code can run without JS error but let see what does it render:

<article data-reactid=".0.1">
    <h2 data-reactid=".0.1.0">Title</h2>
    <p data-reactid=".0.1.1">content</p>
    <div data-reactid=".0.1.2">Last updated by author at 23-11-2018 12:45:30</div>
</article>
the div element is without class name ! so i can't assign CSS style with class selector.

Correction

method 1
use className instead of class:
var Article = React.createClass({
  render:function(){
    return (
      <article>
        <h2>Title</h2>
        <p>content</p>
        <div className="meta">Last updated by author at 23-11-2018 12:45:30</div>
      </article>
    );
  }
});
result :
<article data-reactid=".0.1">
    <h2 data-reactid=".0.1.0">Title</h2>
    <p data-reactid=".0.1.1">content</p>
    <div class="meta" data-reactid=".0.1.2">Last updated by author at 23-11-2018 12:45:30</div></article> 

method 2
use className={' '} pattern for multiple class:
var Article = React.createClass({
  render:function(){
    return (
      <article>
        <h2>Title</h2>
        <p>content</p>
        <div className={`bold meta`}>Last updated by author at 23-11-2018 12:45:30</div>
      </article>
    );
  }
}); 

result:
<article data-reactid=".0.1">
    <h2 data-reactid=".0.1.0">Title</h2>
    <p data-reactid=".0.1.1">content</p>
    <div class="bold meta" data-reactid=".0.1.2">Last updated by author at 23-11-2018 12:45:30</div></article>

Reference

https://stackoverflow.com/questions/32230635/passing-in-class-names-to-react-components

No comments :

Post a Comment