DEV Community

Cover image for creating Components (part I)
anojaa gnanes
anojaa gnanes

Posted on

creating Components (part I)

there are two main ways to creating components in React.now we can discuss about how to create the components in the React.

1.stateless functional components

stateless component is just a plain javascript function which takes props as an argument and returns a react element, A stateless component has no state.

They have 2 main features:
*When rendered they receive an object with all the props that were passed down.
*They must return the JSX to be render.

basic structure for the statelss components

example:-

import React from 'react';
import PropTypes from 'prop-types';
const FirstComponent = props => (



Hello, {props.name}! I am a FirstComponent.

);
FirstComponent.propTypes = {

name: PropTypes.string.isRequired,
}

2.state components

The heart of every React component is its “state”, an object that determines how that component renders & behaves. In other words, “state” is what allows you to create components that are dynamic and interactive.

basic structure for the state components

example:-

import React, { Component } from 'react';
class SecondComponent extends Component {
constructor(props) {
super(props);
this.state = {
toggle: true
};
this.onClick = this.onClick.bind(this);
}
onClick() {
this.setState((prevState, props) => ({
toggle: !prevState.toggle
}));
}
render() {
return (

Hello, {this.props.name}! I am a SecondComponent.


Toggle is: {this.state.toggle}

);
}
}

Latest comments (1)

Collapse
 
savagepixie profile image
SavagePixie • Edited

A good thing to note is that since the introduction of hooks, function components needn't be stateless. So you can make stateless and stateful components with both classes and components.

Also, just a formating trick: You can put your code between two blocks of three back-ticks (`). So you could do

'''javascript
Your code
'''

But with the appropriate back-ticks instead of apostrophes.