4

Quick question. I'm learning react js.

When we create a component, we provide in the render function the html template of the component to render. So far I have only seen small components with very small pieces of html, but I was just wondering what happen if we have a component with a huge html template, is there any way to provide the path to a separate html file? Or we are forced to write all the html directly inside the render function? Thanks!

Antoni4
  • 2,535
  • 24
  • 37
fgonzalez
  • 3,787
  • 7
  • 45
  • 79

2 Answers2

5

You should always write it in the render function. You're not writing HTML in there, you're writing JSX, which is compiled into Javascript. Something like <div className="test"> is converted into React.createElement("div", {className: 'test'});.

You shouldn't have an issue of size as long as you break down large components into a composition of many smaller components. You can include other components by including them in your render function, like this: <SomeComponent someProp="someVal" />.

mash
  • 14,851
  • 3
  • 30
  • 33
4

You can split your render function to the bunch of good-named methods like a partials in old plain html-templates. It's useful to make complex react-components, because you will remove big unreadable html-part from your code.

For example, here is some pseudo-code described this approach:

class NavBar extends React.Component {

  // Render user name and links on profile and logout 
  renderUser() {
    if (!user) return;
    return <div>{user.name}</div>;
  }

  // Render list with nav-bar items if they exists
  renderNavBarItems() {
    if (!user) return;
    return <ul>{this.items.map((i) <li><a href={i.link}>{i.name}</a></li>)}</ul>;
  }

  render() {
    return (<div className="nav-bar">
      {this.renderNavBarItems()}
      {this.renderUser()}
    </div>);
  }
}
Anton Shuvalov
  • 3,560
  • 3
  • 16
  • 20