DEV Community

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

Posted on

5

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}

);
}
}

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top 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.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Instrument, monitor, fix: a hands-on debugging session

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️