react function components code example

Example 1: create react component class

class MyComponent extends React.Component{
    constructor(props){
        super(props);
    };
    render(){
        return(
            <div>
              <h1>
              	My First React Component!
              </h1>
            </div>
        );
    }
};

Example 2: functional component react

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

function App() {
  return (
    <div>
      <Welcome name="Sara" />      <Welcome name="Cahal" />      <Welcome name="Edite" />    </div>
  );
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

Example 3: functional components react

function Comment(props) {
  return (
    <div className="Comment">
      <div className="UserInfo">
        <img className="Avatar"
          src={props.author.avatarUrl}
          alt={props.author.name}
        />
        <div className="UserInfo-name">
          {props.author.name}
        </div>
      </div>
      <div className="Comment-text">
        {props.text}
      </div>
      <div className="Comment-date">
        {formatDate(props.date)}
      </div>
    </div>
  );
}

Example 4: Which function is used to add functionality to a custom component?

AFRAME.registerComponent(..);

Example 5: react function component

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

Example 6: class to functional component react

// convert a class component to a functional component
class MyComponent extends React.Component {
	state: { 
      name: 'Bob' 
    }
	render() {
      return (
        <p>Hello, my name is {this.state.name}</p>
      );
    }
}

const MyComponent = () => {
  const [name, setName] = React.useState('Bob');
  return (<p>Hello, my name is {name}</p>);
}