Please help with the task. I have 2 components: Header, which has a Modal component (for a modal window) and a Main_Part component. I don't know how to make so that on the Create
button values from input were created in the Main_part component.
How can this be done? Thanks
Main_part.js
import React from "react";
import "./Main_Part.css";
export let Main_Part = ({newList}) => {
return (<div className="main">
</div>)
}
Header.js
import React, {useState} from "react";
import "./Header.css";
import {Modal} from "../Modal/Modal";
import {Main_Part} from "../Main_Part/Main_Part";
export let Header = () => {
let [modalActive, setModalActive] = useState(false);
let [newList, setNewList] = useState([]);
let [input, setInput] = useState('');
let addList = (myInput) => {
let newDiscussion = {
id: Math.random(),
task: myInput
}
setNewList([...newList, newDiscussion])
}
let handleInput = (e) => {
setInput(e.target.value)
}
let submitTask = (e) => {
e.preventDefault();
addList(input);
setInput('')
}
return (<header className="header">
<div>
<button onClick={() => setModalActive(true)}>Створити новий список</button>
</div>
<Modal active={modalActive} setActive={setModalActive}>
<form onSubmit={submitTask}>
<input
type="text"
placeholder="Створити"
onChange={handleInput}
/>
<button type="submit" onSubmit={submitTask}>Create</button>
</form>
<button onClick={() => setModalActive(false)}>Закрити</button>
</Modal>
<Main_Part newList={newList}/>
</header>)
}
CodePudding user response:
Here's the simple sample of what you're wanting to do. You just need to pass the input values to Main_Part
and check its for not null definition in Main_Part
:
newList && newList.map((v, i) => v.task)
Here's the example:
import { useState } from "react";
import "./styles.css";
const Main_Part = ({ newList }) => {
return <div className="main">{newList && newList.map((v, i) => v.task)}</div>;
};
const Header = () => {
let [modalActive, setModalActive] = useState(false);
let [newList, setNewList] = useState([]);
let [input, setInput] = useState("");
let addList = (myInput) => {
let newDiscussion = {
id: Math.random(),
task: myInput
};
setNewList([...newList, newDiscussion]);
};
let handleInput = (e) => {
setInput(e.target.value);
};
let submitTask = (e) => {
e.preventDefault();
addList(input);
setInput("");
};
return (
<header className="header">
<form onSubmit={submitTask}>
<input type="text" placeholder="Створити" onChange={handleInput} />
<button type="submit" onSubmit={submitTask}>
Create
</button>
</form>
<button onClick={() => setModalActive(false)}>Закрити</button>
<Main_Part newList={newList} />
</header>
);
};
export default function App() {
return (
<>
<Header />
<Main_Part />
</>
);
}