So my App.js file looks like this:
import React from "react";
import { useState } from "react";
import './App.css';
import Header from "./components/pages/Header";
import NAV from "./NAV";
import Trees from "./components/tree";
function App() {
const [inputField , setInputField] = useState({
first_name: 'Phyag_NZFS3770'
})
const inputsHandler = (e) =>{
setInputField( {[e.target.name]: e.target.value} )
}
const submitButton = () =>{
alert(inputField.first_name)
}
return(
<div className="App">
<NAV genomename={inputField.first_name}/> //this can't be done as the prop value is undefined
<Header title="EumicrobeDB"/>
<h3 style={{ textAlign:"left" }}> Organism List </h3>
<div> <Trees /> </div>
<div>
<input
type="text"
name="first_name"
onChange={inputsHandler}
placeholder="enter the organism id"
value={inputField.first_name}/>
<button onClick={submitButton}>Submit Now</button>
</div>
</div>
)
}
export default App;
Can anyone please modify the code to pass {inputField.first_name} as prop value to my function called NAV? I am in an absolute fix..I am a biologist who is new to React; who has to meet a deadline
CodePudding user response:
This is how you can pass data from parent component to child as a props
.
Example
import React from "react";
import { useState } from "react";
const Header = ({ title }) => {
return <React.Fragment>Hello, {title}</React.Fragment>;
};
function App() {
const [inputField, setInputField] = useState({
first_name: "Phyag_NZFS3770"
});
const inputsHandler = (e) => {
console.log([e.target.name] , e.target.value);
setInputField({ [e.target.name]: e.target.value });
};
const submitButton = () => {
alert(inputField.first_name);
};
return (
<div className="App">
<Header title={inputField.first_name} />
<h3 style={{ textAlign: "left" }}> Organism List </h3>
<div>
<input
type="text"
name="first_name"
onChange={inputsHandler}
placeholder="enter the organism id"
value={inputField.first_name}
/>
<button onClick={submitButton}>Submit Now</button>
</div>
</div>
);
}
export default App;
CodePudding user response:
Your code in this component looks fine as-is. Make sure you're accessing props.genomename
and not props.first_name
in the NAV component.
If you're planning to add more input fields, I'd also suggest you change the inputHandler function to merge with the previous state, rather than replacing it entirely:
const inputsHandler = (e) => {
setInputField({ ...inputField, [e.target.name]: e.target.value })
}