Site icon i2tutorials

ReactJS- React Props

React Props

 

 

React- Props -Example

              Npx create-react -app 

 

 

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

function App() {
 return (
 <div className="App" 
<div className="main-cointainer">
            <h2>Compnent1</h2> 
            </div>
            </div>                 
      );
       } 
export default App;

 

import React from 'react';
export default function Component2() {
 return (
<div className="main-cointainer">
  <h2>Compnent2</h2>

  </div>
    )
}

 

import React from 'react';
export default function Component2(props) {
 return (
   <div className="main-cointainer">
    <h2>Compnent2</h2>
         
<p>{props.data} </p>
        </div>
    )
}

 

import React, { useState } from 'react';
function App() {
 const [state, setstate] = useState({data:""})

 

After this we will create a ChangeState function which will be called onClick of a button

   const changeState = () => {  
         setstate ({data:`
        This is component 2`});


   <Component2 data={state.data} />   
   <div className="main-cointainer">
     <h2>Compnent1</h2> 
     <button  onClick={changeState} >
     Send state 
     </button> 
    </div>

 

Here above we are calling the ChangeState function on a button, which when clicked will display the data/text from Component2.js.

 

Below is the full code of App.js

import React, { useState } from 'react';
import './App.css'
import Component2 from './Component2';


function App() {
  const [state, setstate] = useState({data:""}
    const changeState = () => {  
         setstate ({data:`
        This is component 2`});
       }; 
  return (
    <div className="App">
          <Component2 data={state.data} />   
            <div className="main-cointainer">
                <h2>Compnent1</h2> 
                <button  onClick={changeState} >
                  Send state 
                </button> 
            </div>
        </div>                 
    );
 }
export default App;

 

Below is the output:

 

This is the output after the button is clicked:

 

———-

 

Exit mobile version