Reactjs Props Example With Function and Class Components

04-Apr-2023

.

Admin

Hi Friends,

in this blog we are learing about props. in react js component means javascript function. and function accept attribute and input that's called props. using props we are get dynamic data and we less the code.

Props Example With Function Component


In Function Components we get attribute with "prop.propName". this is the simple function of javascript. In this example we are display user name and email. you can also get array and object.

/src/User.js file

import React from 'react'

function User(prop){

return <div>

<h1>User Name : {prop.name}</h1>

<h1>User email : {prop.email}</h1>

</div>

}

export default User;

/src/App.js file

import React from 'react';

import logo from './logo.svg';

import './App.css';

import User from './User';

function App() {

return (

<div className="App">

<header className="App-header">

<User name="Nicesnippets" email="nicesnippets@gmail.com" />

</header>

</div>

);

}

export default App;

Props Example With Class Component

In class component you can get prop with "this.props" keyword like "this.props.propName". In this component we are get prop with simple way. you can also get array and object.

/src/User.js file

import React from 'react'

class User extends React.Component{

render(){

return(

<div>

<h1>User Name : {this.props.name}</h1>

<h1>User email : {this.props.email}</h1>

</div>

)

}

}

export default User;

/src/App.js file

import React from 'react';

import logo from './logo.svg';

import './App.css';

import User from './User';

function App() {

return (

<div className="App">

<header className="App-header">

<User name="Nicesnippets" email="nicesnippets@gmail.com" />

</header>

</div>

);

}

export default App;

I hope it can help you...

#React.js