I need some help:
- How to use value
name
fromLoginPanel
component after user write it inside the input and click button and use it inside theApp
component. - How to render
LoginPanel
as first and if input name is written and button is clicked switch view to the App component?
I can’t understand that.
My code looks like that.
import React, { useState } from "react";
function LoginPanel() {
const [fname, setName] = useState({
fName: "",
password: "",
});
function handleChange(event) {
const { name, value } = event.target;
setName(prevValue => {
return {
...prevValue,
[name]: value
};
});
}
return (
<div className="container">
<h1>
Log In ↓
</h1>
<form>
<input
onChange={handleChange}
name="fName"
value={fname.fName}
placeholder="First Name"
/>
<input
type='password'
name="password"
placeholder="Password"
/>
<button>Submit</button>
</form>
</div>
);
}
export default LoginPanel;
import React, { useState } from "react";
import Header from "./Header";
import Footer from "./Footer";
import Note from "./Note";
import CreateArea from "./CreateArea";
function App() {
const [notes, setNotes] = useState([]);
function addNote(newNote) {
setNotes((prevNotes) => {
return [...prevNotes, newNote];
});
}
function deleteNote(id) {
setNotes((prevNotes) => {
return prevNotes.filter((noteItem, index) => {
return index !== id;
});
});
}
return (
<div>
<Header />
<CreateArea onAdd={addNote} />
{notes.map((noteItem, index) => {
return (
<Note
key={index}
id={index}
title={noteItem.title}
content={noteItem.content}
onDelete={deleteNote}
/>
);
})}
<Footer />
</div>
);
}
export default App;
import React, { useState } from "react";
import App from "./App";
import LoginPanel from "./LoginPanel";
function Main() {
const [isLogged, setLogged] = useState(false);
return (
<div>
{!isLogged ? <LoginPanel /> : <App />}
</div>
)
}
export default Main
I tried a lot of react tutorials and documentation.
I want use value name
from LoginPanel
component after user write it inside the input and click button and use it inside the App
component and to render LoginPanel
as first and if input name is written and button is clicked switch view to the App
component?
3
Answers
Thank you for help! I changed the code. It works and looks like that:
Use the name useState hook in the Main file and pass it as a props to the LoginPanel, Also pass the same hook to the App file to use the data inside.To switch between App and LoginPanel:- pass the isLogged hook to both of them and write a function inside both the files to switch when a button is clicked.
Lift the "name" state up to the parent,
Main
, and pass the state and state updater function down as props to the components. When the form is submitted, update the state.For more details see Sharing State Between Components.
Example: