JSX Rules

1) Normal Function or Arrow Function

  • We can write normal functions  or Arrow function
  • Arrow function can be written without return as well as explained in below example.
				
					import React from "react";

function App() {
  return <div>Normal function</div>;
}
export default App;
				
			
				
					const App = () => {
  return <div>arrow function</div>;
};
				
			
				
					const App = () => <div>arrow function without return</div>;
				
			

2) JSX internally converts

				
					const App = () => {
  return <div>arrow function</div>;
};

//This gets converted to as below. Use Babel to try it out.

const App = () => {
  return React.createElement("div", {}, "arrow function");
};
				
			
				
					const App = () => {
  return (
    <div>
      <h1>h1 inside div</h1>
    </div>
  );
};
				
			
				
					const App = () => {
   return React.createElement("div", {}, React.createElement("h1", {}, "h1 inside div"));
};
				
			

3) Wrap up in div or fragment if more than html tag

				
					const App = () => {
  return (
    <>
      <h1>test1</h1>
      <h2>test2</h2>
    </>
  );
};

				
			
				
					const App = () => {
   return React.createElement("div", {}, React.createElement("h1", {}, "h1 inside div"));
};

				
			
				
					const App = () => {
  return <div>arrow function</div>;
};
				
			

4) camelCase for html attribute

  • onClick html attribute is camelCase
  • you can write inline function like in second button
  • Or you can create the function separately like in 1st button.
				
					const App = () => {
  const buttonClick = (e, j) => {
    console.log(e);
    console.log(j);
  };
  return (
    <div>
      <button onClick={buttonClick}>test</button>
      <button onClick={() => buttonClick("I am called", 2)}>test</button>
    </div>
  );
};
				
			

5) Component should start with capital letter

  • App is the component name. App starts with capital A. So the name must be capitalized
				
					const App = () => {
  const buttonClick = (e, j) => {
    console.log(e);
    console.log(j);
  };
  return (
    <div>
      <button onClick={buttonClick}>test</button>
      <button onClick={() => buttonClick("I am called", 2)}>test</button>
    </div>
  );
};
				
			

6) className instead of class

  • To apply classname we used to apply class in html tags
  • But now we ought to use className
				
					 const App = () => {
   return <div className="orangeRed">Orange Red Div</div>;
 };
				
			

7) close every element

Leave a Comment