Search code examples
javascriptreactjsreact-propsreact-component

How to display one component's input value to another components using props in REACTJS?


This is a simple project where I want to display firstComponent's input value to another components (secondComponent) but I am failed to display another component. Now, I need the suggestion to do this projects and I have given the codes in below,

App.js:

import React from 'react';
import './App.css';
import First from './components/firstComponent';
import Second from './components/secondComponent';

function App() {
return (
<div className="App">
<br/><br/>
<First />
<hr/> <hr>
<Second/>
</div>
);
}

export default App;

firstComponent.jsx:

import React from 'react';

const firstComponent = ()=> {
function handleChange(event) {
const inputValue = event.target.value;
console.log(inputValue);
}
return (
<div>
<h1><u>First Component</u> </h1>
<input type="text" style={{ width: "500px", height:"30px" }} onChange={handleChange}/>
</div>
)
}

export default firstComponent

;

secondComponent.jsx:

import React from 'react';

const secondComponent = (props) => {
return (
<div>
  <h1><u>Second Component</u> </h1>
  <h4>{this.props.inputValue}</h4>
</div>
)
}

export default secondComponent;

 

Note: I have attached the output page in attach file section, please concern there.

enter image description here


Solution

  • Please try the code given below. This will hopefully fulfill your requirement.

    App.js

    
    import FirstComponent from './FirstComponent'
    const App = () => {
        return ( 
           <>
            <FirstComponent / >
            </>
        )
    }
    
    export default App
    
    

    FirstComponent.js

    
    import React, { useState } from "react";
    import SecondComponent from "./error";
    
    function FirstComponent() {
      const [inputData, setInputData] = useState();
    
      return (
        <>
          <div>
            <h1>
              <u>First Component</u>{" "}
            </h1>
            <input
              type="text"
              style={{ width: "500px", height: "30px" }}
              onChange={(e) => setInputData(e.target.value)}
            />
            <br />
            <SecondComponent inputValue={inputData} />
          </div>
        </>
      );
    }
    export default FirstComponent;
    
    
    

    SecondComponent.js

    
    import React from 'react';
    
    const secondComponent = (props) => {
    return (
    <div>
      <h1><u>Second Component</u> </h1>
      <h4>{props.inputValue}</h4>
    </div>
    )
    }
    
    export default secondComponent;