Skip to content

ross-u/02-react-props-intro

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

React | Props introduction


Clone the starter code repo

git clone https://github.com/ross-u/02-react-props-intro.git

cd 02-react-props-intro

code .

Install the dependencies

npm i

Component can have internal state

  • state is an object in react class components used to save the data/state related to the current component.

  • state represents data that is private to every React class component itself.


MyComponent.js
// src/MyComponent.js

import React from 'react';

class MyComponent extends React.Component {
  state = {
    name: 'Sarah',
  };

  render() {
    return (
      <div>
        <p> Hello {this.state.name}</p>
      </div>
    );
  }
}

export default MyComponent;


// `state` represents data that is private to every class component itself
// ( it stores data that only component can access and change)

Using state - Image

Step 1 (using state ) - Image


Passing props (data) to a component

React components have ability to receive data from outside.

Meaning that we can pass / inject data to the components.

This is done by creating custom named attributes with the value (we are passing to) on each component element. This custom named attributes are called props.


App.js
// src/App.js

import React from 'react';
import './App.css';
import MyComponent from './MyComponent';

class App extends React.Component {
  render() {
    return (
      <div>
        {/*          city="Barcelona" is a prop ( data we pass to MyComponent )  */}
        <MyComponent city="Barcelona" />	
        <MyComponent />
      </div>
    );
  }
}

export default App;

MyComponent.js
// src/MyComponent.js

import React from 'react';

class MyComponent extends React.Component {
  state = {
    name: 'Sarah',
  };

  render() {
    return (
      <div>
        <p> Hello {this.state.name}</p>
        <p> Welcome to {this.props.city}</p>  
      {/*  
        props represent atributtes set on the component
      	and are used to pass data to the component from the outside  
      */}
      </div>
    );
  }
}

export default MyComponent;

Passing props to a component - Image

Passing props to a component - Image


Summary of using props and state


Summary of using props and state - Image Summary of using props and state - Image


About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published