m00saca m00saca - 3 months ago 8
React JSX Question

Method in React component not rendering HTML

Hello I am fairly new to React and I have having a bit of trouble I don't think I should be experiencing. I have a component that has two methods the first method is

test
and the second is the standard
render
. Check it out:

var Projects = React.createClass({
test: function(){
return(
<h1>Why</h1>
)
},
render: function(){

return (
<div className="postWrapper">
<div id="projectsHeader">
<h1>Projects</h1>
</div>
<div id="projectsBody">
{this.test}
</div>
</div>

)
}
});


The problem is when I am calling the
test
method using
{this.test}
within the Projects component, nothing renders. I want this method to be available within the component so I can eventually render multiple items programmatically. What am I doing wrong? Since I am using React Router I don't know how to pass children props when they are also being rendered programmatically using
{this.props.children}
, which is what I tried to do within the
MasterLayout
component but became stuck. I'll provide the rest of my code for context, any help is greatly appreciated.

var MasterLayout = React.createClass({
mixins: [History],
getInitialState: function(){
return{
hello: {}
}
},
renderProjects: function(){
return(
<div>
<h1>This better work</h1>
</div>
)
},
render: function(){
return(
<div id="container">
<Navigation />
<div id="content">
{this.props.children}
</div>
</div>
)

}
});

var Projects = React.createClass({
test: function(){
return(
<h1>Why</h1>
)
},
render: function(){

return (
<div className="postWrapper">
<div id="projectsHeader">
<h1>Projects</h1>
</div>
<div id="projectsBody">
{this.test}
</div>
</div>

)
}
});

var TestPage = React.createClass({

render: function(){
return(
<div className="postWrapper">
<div id="postHeader">
<div id="titleDate">
<h2>This is a test blog title</h2>
<span>1/1/2016</span>
</div>
<div id="testFrame">
</div>
</div>
<div id="postBody">
<p>...</p>
</div>
</div>
)
}
})


var routes = (
<Router history={history}>
<Route path="/" component={MasterLayout}>
<IndexRoute component={TestPage}></IndexRoute>
<Route path="/projects" component={Projects}></Route>
</Route>
</Router>
)



ReactDOM.render(routes, document.getElementById("app"));

Answer

You are not calling test; you're trying to output the function itself, not the result of the function. Just add some () after this.test:

var Projects = React.createClass({
    test: function() {
      return(
          <h1>Why</h1>
        )
    },
    render: function() {
      return (
          <div className="postWrapper">
            <div id="projectsHeader">
              <h1>Projects</h1>
            </div>
            <div id="projectsBody">
              {this.test()}
            </div>
          </div>
      )
    }
});
Comments