• Register
160 points
4

Creating a new React Component

Using class

When you use class to create react component, you must extend React.Component.

In React component’s constructor() function is used to get data from the parent class.

The constructor() function is optional.

Inside in constructor(), you must describe super(props) to notify the super component and you can initialize the component’s state.

 

When you create React component,  you must declare render() function to render Html view to the viewport.

//save NewComponent.jsx

import React from 'react'

class NewComponent extends React.Component {
 constructor(props) {
   super(props);
 }
}

 render() {

   return (
     <h1>Hello</h1>
    )
  }
}
 
export default NewComponent;

 

Using function

When you use the function to create the component, the function can accept props -data from the parent component- as the parameter.

At this point, the parameter must be around {}.

export default function NewComponent({props}) {

  return (

   <h1>Hello</h1>

  )

}

*****

The component can have any name, but you must export it as a 

export default 

 

If you want to use this component, you should import this component;

//save othercomponent.jsx

import React from 'react'
import NewComponent as App from ‘./NewComponent’;

export default class OtherComponent extends React.Component {

   render() {

     return (

       <div>

        <App></App>
        kodlogs

      </div>

    )

  }

}

 

You can import React component with alias name:

   import NewComponent as App from ‘./NewComponent’;

After this, you can use App instead of NewComponent.

  return <App></App>

-output

Hello
kodlogs
160 points
4