How to append data from a form in React? - javascript

I have two input fields here and I would like to create a new cards object by clicking submit. I got as far as displaying the object in the dev tools, but i can't manage to display this data from the input fields as a new card.
I suspect it has something to do with formdata, append and state management.
Does anyone have an idea how this works?
My App.js:
import "./App.css";
import Card from "./components/Card";
import Header from "./components/Header";
import CardComponents from "./components/CardComponents";
import CreateForm from "./components/Form";
export default function App() {
const colorCard = [
{
name: "Card1",
id: "234",
colorCode: "#ccc",
},
{
name: "Card2",
id: "2",
colorCode: "#4c6ef5",
},
{
name: "Card3",
id: "3",
colorCode: "#82c91e",
},
{
name: "Card4",
id: "4",
colorCode: "#12b886",
},
{
name: "Card5",
id: "5",
colorCode: "#00FFFF",
},
{
name: "Card6",
id: "7",
colorCode: "#9FE2BF",
},
{
name: "Card8",
id: "5",
colorCode: "#DE3163",
},
{
name: "Card9",
id: "5",
colorCode: "#50C878",
},
{
name: "Card10",
id: "5",
colorCode: "#40E0D0",
},
];
return (
<main>
<Header />
<CreateForm />
<ul>
{colorCard.map((card) => (
<CardComponents
key={card.id}
color={card.colorCode}
name={card.name}
/>
))}
</ul>
</main>
);
}
Form.js component:
import { useState } from "react";
const CreateForm = () => {
const [value, setValue] = useState("");
const [code, setCode] = useState("");
const submitHandler = (event) => {
event.preventDefault();
const newColorBox = { value, code };
console.log(newColorBox);
};
return (
<form onSubmit={submitHandler}>
<h2>Add Card</h2>
<input
type="text"
required
placeholder="Name your Card"
value={value}
onChange={(event) => setValue(event.target.value)}
></input>
<br></br>
<input
type="text"
placeholder="Name your Color Code"
required
value={code}
onChange={(event) => setCode(event.target.value)}
></input>
<br></br>
<button type="submit">Submit your Card</button>
<p> CardName: {value}</p>
<p>ColorCode: {code}</p>
</form>
);
};
export default CreateForm;

1 Add:
const [cards,setCards]=useState(/*you car insert your initial data in app.js*/)
pass setCards() to form.js and call it inside of submitHandler.

Related

view more and view less with useState hook in react js

I am fresh to react and useState hooks (still learning). I want to create show more/less button with use of an Array of images and React hooks. I import the images into div, I wanted to set button on the last and the show the images on the click of button.
I am getting the error:
text.slice is not function
The thing is, the code is written with use of function component.
here's my code:
import React from 'react';
import { useState } from 'react';
import '../assets/css/Product.css';
const ReadMore = ({ children }) => {
const text = children;
const [isReadMore, setIsReadMore] = useState(true);
const toggleReadMore = () => {
setIsReadMore(!isReadMore);
};
return (
<p className='text'>
{isReadMore ? text.slice(0, 150) : text}
<span onClick={toggleReadMore} className='read-or-hide'>
{isReadMore ? '...read more' : ' show less'}
</span>
</p>
);
};
export const Product = () => {
const card_image = [
{
image: 'CLT_Food_BeverageBar.jpg',
title: 'Charlotte',
subtitle: '(CLT)',
button: 'Explore Lounge',
},
{
image: 'Centurion_Cropped_0001_Bar.jpg',
title: 'Dallas',
subtitle: '(DFW)',
button: 'Explore Lounge',
},
{
image: 'DEN_GameRoom-LR_1200x540.jpg',
title: 'Denver',
subtitle: '(DEN)',
button: 'Explore Lounge',
},
{
image: 'IAH_Bar&Buffet_1200x600.jpg',
title: 'Houston',
subtitle: '(IAH)',
button: 'Explore Lounge',
},
{
image: 'amxtcl_Lounge_01_cmyk_1200x600.jpg',
title: 'Las Vegas',
subtitle: '(LAS)',
button: 'Explore Lounge',
},
{
image: 'LAX_hero.jpg',
title: 'Los Angeles',
subtitle: '(LAX)',
button: 'Explore Lounge',
},
{
image: 'LoungeAreaTalent1200x600.jpg',
title: 'Miami',
subtitle: '(MIA)',
button: 'Explore Lounge',
},
{
image: 'JFK_Carousel_3.jpg',
title: 'New York',
subtitle: '(JFX)',
button: 'Explore Lounge',
},
];
return (
<div>
<div className='container'>
<ReadMore>
<div className='row introduction'>
{card_image.map((card) => (
<div className='col-lg-3 pt-5'>
<div
className='location_card'
style={{
backgroundImage: `url(${process.env.REACT_APP_ASSET_URL}/card_image/${card.image})`,
objectFit: 'cover',
}}>
<div className='location-overly'>
<h3 className='h2'>
{card.title}
<br />
{card.subtitle}
</h3>
<button
type='button'
class='btn_product '>
{card.button}
</button>
</div>
</div>
</div>
))}
</div>
</ReadMore>
</div>
</div>
);
};
I think you should use conditional rendering, this means that when a state changes, your UI also changes. Sorry, I don't think I explained it that well, so here's some example code.
import * from x "xyz xyz";
const App = () => {
const [showMore, setShowMore] = useState(false);
if(showMore){
return(
<MoreStuff/>
);
}
return(
<DefaultStuff/>
);
}
Resources:
https://www.digitalocean.com/community/tutorials/7-ways-to-implement-conditional-rendering-in-react-applications
https://www.w3schools.com/react/react_conditional_rendering.asp
https://zh-hans.reactjs.org/docs/conditional-rendering.html
import { useState } from 'react';
const allCars = [
{ name: 'Audi', country: 'Germany' },
{ name: 'BMW', country: 'Germany' },
{ name: 'Chevrolet', country: 'USA' },
{ name: 'Citroen', country: 'France' },
{ name: 'Hyundai', country: 'South Korea' },
{ name: 'Mercedes-Benz', country: 'Germany' },
{ name: 'Renault', country: 'France' },
{ name: 'Seat', country: 'Spain' },
];
function CarFilter() {
const [showMoreData, setShowMoreData] = useState(3);
const showMore = () => {
if (showMoreData === 3) {
setShowMoreData(allCars.length);
} else if (showMoreData > 3) {
setShowMoreData(3);
}
};
return (
<div className="container">
<ul>
{allCars.slice(0, showMoreData).map((car, i) => (
<li key={i}>
{car.name} - {car.country}
</li>
))}
</ul>
{allCars.length > 3 && (
<button type="button" onClick={showMore}>
{showMoreData > 3 ? 'Show More ' : 'Show less'}
</button>
)}
</div>
);
}
export default CarFilter;

Change text in radio button dynamically in react-native using Hooks

Today i want to create something like form in react native that looks like
It's pretty simple. i used this lib for radio button. However i want to change this text in the button when i click button next. I used following code.
import React, { useState, useRef } from "react";
import { StyleSheet, View, Button } from "react-native";
import RadioButtonRN from "radio-buttons-react-native";
export default function App() {
const numRef = useRef(0);
const questions = [
{
question: "What is localhost's IP address?",
answers: [
{ id: "1", text: "192.168.1.1" },
{ id: "2", text: "127.0.0.1", correct: true },
{ id: "3", text: "209.85.231.104" },
{ id: "4", text: "66.220.149.25" },
],
},
{
question: "What kind of11 fruit was used to name a computer in 1984?",
answers: [
{ id: "1", text: "Blackberry" },
{ id: "2", text: "Blueberry" },
{ id: "3", text: "Pear" },
{ id: "4", text: "Apple", correct: true },
],
},
];
return (
<View>
<RadioButtonRN
data={questions[numRef.current].answers.map((item) => ({
label: item.text,
correct: item.correct,
}))}
selectedBtn={(e) => {
console.log(e);
}}
/>
<Button
title="Next"
onPress={() => {
numRef.current = numRef.current + 1;
}}
/>
</View>
);
}
So right now when i clicked on the next button, the only thing thats updated is variable
numRef
But questions[numRef.current] doesn't update text in the button.
How can i fix that?
Changing the value of a ref doesn't result in a re-render. For data that, when it gets changed, should result in a re-render, you should use state instead.
export default function App() {
const [num, setNum] = useState(0);
// ...
data={questions[num].answers.map((item) => ({
// ...
onPress={() => {
setNum(num + 1)l
}}

Display React Bootstrap's Modal when you press a button

Goal:
Display react bootstrap's modal when you press the button 'Open Modal'
Problem:
I do not know how to make it to show bootstrap's modal when I press the button 'Open Modal'
What part am I missing?
Stackblitz:
https://stackblitz.com/edit/react-bootstrap-examples-suktpo?
Info:
*I'm newbie in Reactjs
Thank you!
index.html
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<div id="root"></div>
index.js
import React, { Component } from 'react';
import { render } from 'react-dom';
import './style.css';
import DisplayModalContent from './DisplayModalContent';
import { Modal, Button } from 'react-bootstrap';
class App extends Component {
constructor() {
super();
this.state = {
openItem: null,
items: [
{
firstName: 'Josef',
lastName: 'Anderson',
key: 'josef.anderson',
startYear: 2021,
startMonth: 2
},
{
firstName: 'Jim',
lastName: 'West',
key: 'jim.west',
startYear: 2020,
startMonth: 3
},
{
firstName: 'Joe',
lastName: 'West',
key: 'joe.west',
startYear: 1998,
startMonth: 10
}
],
firstName: '',
lastName: ''
};
}
handleOpenModal = openItem => {
this.setState({ openItem });
};
handleCloseModal = () => {
this.setState({ openItem: null });
};
handleOpenItemValue = e => {
let { name, value } = e.target;
this.setState({
openItem: { ...this.state.openItem, [name]: value }
});
};
handleSubmit = () => {
console.log(document.getElementsByName('startMonth')[0].value);
alert(
JSON.stringify({
test: document.getElementsByName('startMonth')[0].value
})
);
};
render() {
const { items, openItem } = this.state;
return (
<div>
<table border="1">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th />
</tr>
</thead>
<tbody>
{items.map(item => {
const { firstName, lastName, key } = item;
return (
<tr key={key}>
<td>{firstName}</td>
<td>{lastName}</td>
<td>
<button onClick={() => this.handleOpenModal(item)}>
Open Modal
</button>
</td>
</tr>
);
})}
</tbody>
</table>
<DisplayModalContent item={openItem} />
</div>
);
}
}
render(<App />, document.getElementById('root'));
DisplayModalContent.js
import React, { Component } from 'react';
import { render } from 'react-dom';
import './style.css';
import { Modal, Button } from 'react-bootstrap';
const options = [
{ value: 1, label: 'Jan' },
{ value: 2, label: 'Feb' },
{ value: 3, label: 'Mars' },
{ value: 4, label: 'April' },
{ value: 5, label: 'May' },
{ value: 6, label: 'June' },
{ value: 7, label: 'July' },
{ value: 8, label: 'August' },
{ value: 9, label: 'Sept' },
{ value: 10, label: 'Oct' },
{ value: 11, label: 'Nov' },
{ value: 12, label: 'Dec' }
];
class DisplayModalContent extends Component {
constructor() {
super();
this.state = {
openItem: null,
firstName: '',
lastName: ''
};
}
componentDidUpdate(s) {
if (JSON.stringify(this.props) !== JSON.stringify(s)) {
this.setState({ openItem: this.props.item });
}
}
handleOpenModal = openItem => {
this.setState({ openItem });
};
handleCloseModal = () => {
this.setState({ openItem: null });
};
handleOpenItemValue = e => {
let { name, value } = e.target;
this.setState({
openItem: { ...this.state.openItem, [name]: value }
});
};
handleSubmit = () => {
console.log(document.getElementsByName('startMonth')[0].value);
alert(
JSON.stringify({
test: document.getElementsByName('startMonth')[0].value
})
);
};
hideShowModal = () => {
this.setState({ isModalOpen: !this.state.isModalOpen });
};
render() {
const { items, openItem } = this.state;
return (
<div>
{openItem !== null && (
<div isOpen={true}>
<Button variant="primary" onClick={() => this.hideShowModal()}>
Click to hide/show
</Button>
<Modal
show={this.state.isModalOpen}
onHide={() => this.hideShowModal()}
>
<Modal.Header closeButton>
<Modal.Title>This is modal title</Modal.Title>
</Modal.Header>
<Modal.Body>
<p>
First Name:
<br />
<input
type="text"
id="firstName"
name="firstName"
value={openItem.firstName}
onChange={e => this.handleOpenItemValue(e)}
/>
<input
type="text"
id="lastName"
name="lastName"
value={openItem.lastName}
onChange={e => this.handleOpenItemValue(e)}
/>
</p>
</Modal.Body>
<Modal.Footer>
<Button variant="secondary">CLOSE</Button>
<Button variant="primary">SAVE</Button>
</Modal.Footer>
</Modal>
</div>
)}
</div>
);
}
}
export default DisplayModalContent;
you don't have to use the state in the two components, just define the state in the parent component and pass it as a prop to the child component.
index.js
import React, { Component } from "react";
import DisplayModalContent from "./DisplayModalContent";
import { Modal, Button } from "react-bootstrap";
const items = [
{
firstName: "Josef",
lastName: "Anderson",
key: "josef.anderson",
startYear: 2021,
startMonth: 2
},
{
firstName: "Jim",
lastName: "West",
key: "jim.west",
startYear: 2020,
startMonth: 3
},
{
firstName: "Joe",
lastName: "West",
key: "joe.west",
startYear: 1998,
startMonth: 10
}
];
class App extends Component {
constructor() {
super();
this.state = {
open: false,
openItem: null,
items: [],
firstName: "",
lastName: ""
};
}
componentDidMount() {
this.setState({ items });
}
handleOpenModal = (openItem) => {
this.setState({ openItem, open: true });
};
handleCloseModal = () => {
this.setState({ open: false });
};
handleOpenItemValue = (e) => {
let { name, value } = e.target;
this.setState({
openItem: { ...this.state.openItem, [name]: value }
});
};
handleSubmit = (key) => {
const { openItem, items } = this.state;
const updatedItems = items.filter((i) => i.key !== key);
this.setState({
open: false,
items: [...updatedItems, openItem]
});
// console.log(document.getElementsByName("startMonth")[0].value);
// alert(
// JSON.stringify({
// test: document.getElementsByName("startMonth")[0].value
// })
// );
};
render() {
const { items, openItem, open } = this.state;
return (
<div>
<table border="1">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th />
</tr>
</thead>
<tbody>
{items &&
items.map((item) => {
const { firstName, lastName, key } = item;
return (
<tr key={key}>
<td>{firstName}</td>
<td>{lastName}</td>
<td>
<button onClick={() => this.handleOpenModal(item)}>
Open Modal
</button>
</td>
</tr>
);
})}
</tbody>
</table>
<DisplayModalContent
item={openItem}
isOpen={open}
onClose={this.handleCloseModal}
onSubmit={this.handleSubmit}
handleOpenItemValue={(e) => this.handleOpenItemValue(e)}
/>
<br />
<div> {JSON.stringify(items)} </div>
</div>
);
}
}
export default App;
DisplayModalContent.js
import React, { Component } from "react";
import { Modal, Button } from "react-bootstrap";
const options = [
{ value: 1, label: "Jan" },
{ value: 2, label: "Feb" },
{ value: 3, label: "Mars" },
{ value: 4, label: "April" },
{ value: 5, label: "May" },
{ value: 6, label: "June" },
{ value: 7, label: "July" },
{ value: 8, label: "August" },
{ value: 9, label: "Sept" },
{ value: 10, label: "Oct" },
{ value: 11, label: "Nov" },
{ value: 12, label: "Dec" }
];
class DisplayModalContent extends Component {
render() {
const { item, isOpen, onClose, handleOpenItemValue, onSubmit } = this.props;
return (
<div>
<div>
<Modal show={isOpen} onHide={onClose}>
<Modal.Header closeButton>
<Modal.Title>This is modal title</Modal.Title>
</Modal.Header>
<Modal.Body>
<p>
First Name:
<br />
<input
type="text"
id="firstName"
name="firstName"
value={item && item.firstName}
onChange={(e) => handleOpenItemValue(e)}
/>
<input
type="text"
id="lastName"
name="lastName"
value={item && item.lastName}
onChange={(e) => handleOpenItemValue(e)}
/>
</p>
</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={onClose}>
CLOSE
</Button>
<Button variant="primary" onClick={() => onSubmit(item.key)}>
SAVE
</Button>
</Modal.Footer>
</Modal>
</div>
</div>
);
}
}
export default DisplayModalContent;
Live working Demo
I was reviewing your code and I see you're using this.state.isModalOpen to show the modal, but in the DisplayModalContent component that state is never updated when you're receiving the props from your index. So, the easy fix for that is update isModalOpen when you are receiving the props. However, from my experience I would recommend do not use a new state to handle the modal open state in the DisplayModalContent component, you can use it directly from the props:
<DisplayModalContent
item={openItem}
isOpen={!!openItem}
onClose={this.handleCloseModal}
/>
and in your DisplayModalContent component, you can replace any local state and in order to use the component props:
...
<Modal
show={this.props.isOpen}
onHide={this.props.onClose}
>
...
By doing this your code will be more simple and readable.

Select dependent on reactjs with react-select

I'm developing an App in ReactJS, and I have a page where I want to show two select, one dependent on the other.
I'm using react-select and #material-ui.
In dates:
[
{
"id": 1,
"name": "202001"
},
{
"id": 2,
"name": "202002"
},
{
"id": 3,
"name": "202003"
},
{
"id": 4,
"name": "202004"
},
{
"id": 5,
"name": "202005"
},
{
"id": 6,
"name": "202006"
},
{
"id": 7,
"name": "202007"
}
]
I have a list of dates that are available to select.
import React, { useState, useEffect } from "react";
import Select from "react-select";
...
const App = () => {
...
const DateA = dates.map((item) => ({
value: item.id,
label: item.name,
}));
const DateB = dates.map((item) => ({
value: item.id,
label: item.name,
}));
const [dateA, setDateA] = React.useState(null);
const [dateB, setDateB] = React.useState(null);
function handleChangeDateA(value) {
setDateA(value);
}
function handleChangeDateB(value) {
setDateB(value);
}
return (
<div className="App">
<div className="col-3">
<Select
classes={classes}
styles={selectStyles}
inputId="DateA"
TextFieldProps={{
label: "DateA",
InputLabelProps: {
htmlFor: "DateA",
shrink: true,
},
placeholder: "DateA...",
}}
options={DateA}
components={components}
value={dateA}
onChange={handleChangeDateA}
/>
</div>
<div className="col-3">
<Select
classes={classes}
styles={selectStyles}
inputId="DateB"
TextFieldProps={{
label: "DateB",
InputLabelProps: {
htmlFor: "DateB",
shrink: true,
},
placeholder: "DateB...",
}}
options={DateB}
components={components}
value={dateB}
onChange={handleChangeDateB}
/>
</div>
</div>
);
};
export default App;
The idea is that the DateB select take dates greater than the ones selected in the DateA select.
How can I do this, suggestions?
Try this
useEffect(() => {
if (condition) {
setDateB(value)
}
}, [DateA])

React call a function from other component

I'm new to ReactJS and I'm doing a simple CRUD with ReactJS.
I want to add a new Hero to a list of Heroes in class HeroModel. However I don't know how to call the function AddHero in HeroModel.js from AddHero.js.
Here is my code:
HeroModel.js
import React, { Component } from 'react';
class HeroModel {
state = {
Heroes: [
{ Id: 1, Name: "hero1", Dob: new Date("1-1-2017"), Stocked: true, Price: 1.50 },
{ Id: 2, Name: "hero2", Dob: new Date("5-31-2018"), Stocked: false, Price: 2.50 },
{ Id: 3, Name: "hero3", Dob: new Date("2019"), Stocked: true, Price: 3.50 },
{ Id: 4, Name: "hero4", Dob: new Date("4-20-2010"), Stocked: false, Price: 4.50 },
{ Id: 5, Name: "hero5", Dob: new Date("12-31-2018"), Stocked: true, Price: 5.50 },
]
}
GetAllHeroes() {
return this.state.Heroes;
}
AddHero(name, dob, stocked, price) {
let id = this.state.Heroes.length + 1;
this.state.Heroes = [...this.state.Heroes,
{ Id: id, Name: name, Dob: dob, Stocked: stocked, Price: price }];
}
}
export default HeroModel;
AddHero.js
import React, { Component } from 'react';
import HeroModel from './HeroModel';
class AddHero extends Component {
constructor(props) {
super(props);
this.state = {
Id: 0, Name: "", Dob: new Date(), Stocked: true, Price: 0
};
}
onNameChange(e) {
this.setState({
Name: e.target.value
});
}
onDobChange(e) {
this.setState({
Dob: e.target.value
});
}
onStockedChange(e) {
this.setState({
Stocked : e.target.value
});
}
onPriceChange(e) {
this.setState({
Price : e.target.value
});
}
onSave(e){
//----I get stuck here-----
// (new HeroModel).AddHero(
// this.state.Name, this.state.Dob,
// this.state.Stocked, this.state.Price);
}
render() {
return (
<div>
<h1>Add hero</h1>
<form>
<div className="form-group">
<label>Name </label>
<input type="text" onChange={this.onNameChange.bind(this)}></input>
</div>
<div className="form-group">
<label>Dob </label>
<input type="date" onChange={this.onDobChange.bind(this)} defaultValue={new Date().toISOString().substr(0, 10)}></input>
</div>
<div className="form-group">
<label>Stocked </label>
<input type="checkbox" onChange={this.onStockedChange.bind(this)} ></input>
</div>
<div className="form-group">
<label>Price </label>
<input type="text" onChange={this.onPriceChange.bind(this)}></input>
</div>
<button onClick={this.onSave.bind(this)}>Save</button>
</form>
</div>
);
}
}
export default AddHero;
Please help me to add a new Hero to a list of Heroes in HeroMode.js.
I comment in function onSave(e) where I get stuck.
Thank you in advanced.
Edit, for redux implementation, see this sandbox: https://codesandbox.io/s/simple-reactredux-flow-l9oq4
To call a function defined in another function, you need to pass it down as a property. This creates a Parent-Child relationship.
Let's consider the following:
Your Parent-component holds the list of Heroes in its state.
Your Parent-component has a function that lets you add more heroes.
We will call it createNewHero()
Your Parent-component passes createNewHero() down as a prop to the
child, AddHero
AddHero holds input data in its state, we will pass that data as an object to the prop, createNewHero(). Effectively passing the data upwards.
WhencreateNewHero() is called, its execution context is bound to
the parent component. So when this.setState() is executed, the keyword, this points to HeroModel's state.
When complete, we add a single Hero to the list, thus changing the
state, causing our component to re-render.
Checkout the following sandbox to see this in action: https://codesandbox.io/s/frosty-dawn-l9oq4
HeroModel (Parent)
import React from "react";
import ReactDOM from "react-dom";
import AddHero from "./AddHero";
import "./styles.css";
class HeroModel extends React.Component {
state = {
Heroes: [
{
Id: 1,
Name: "hero1",
Dob: new Date("1-1-2017"),
Stocked: true,
Price: 1.5
},
{
Id: 2,
Name: "hero2",
Dob: new Date("5-31-2018"),
Stocked: false,
Price: 2.5
},
{
Id: 3,
Name: "hero3",
Dob: new Date("2019"),
Stocked: true,
Price: 3.5
},
{
Id: 4,
Name: "hero4",
Dob: new Date("4-20-2010"),
Stocked: false,
Price: 4.5
},
{
Id: 5,
Name: "hero5",
Dob: new Date("12-31-2018"),
Stocked: true,
Price: 5.5
}
]
};
createNewHero = newHero => {
this.setState({
...this.state,
Heroes: [...this.state.Heroes, newHero]
});
};
renderHeros = () => {
const { Heroes } = this.state;
return Heroes.map(hero => {
return <div>{hero.Name}</div>;
});
};
render() {
return (
<div>
{this.renderHeros()}
<AddHero createNewHero={this.createNewHero} />
</div>
);
}
}
export default HeroModel;
AddHero (Child)
import React from "react";
class AddHero extends React.Component {
constructor(props) {
super(props);
this.state = {
Id: 0,
Name: "",
Dob: new Date(),
Stocked: true,
Price: 0
};
}
onSave = e => {
e.preventDefault();
const { Id, Name, Stocked, Price } = this.state;
const newHero = {
Id: Id,
Name: Name,
Dob: new Date(),
Stocked: Stocked,
Price: Price
};
this.props.createNewHero(newHero);
};
onChange = e => {
this.setState({
[e.target.name]: e.target.value
});
};
render() {
return (
<div>
<h1>Add hero</h1>
<form>
<div className="form-group">
<label>Name </label>
<input type="text" onChange={this.onChange} name="Name" />
</div>
<div className="form-group">
<label>Dob </label>
<input
type="date"
onChange={this.onChange}
defaultValue={new Date().toISOString().substr(0, 10)}
name="Dob"
/>
</div>
<div className="form-group">
<label>Stocked </label>
<input type="checkbox" onChange={this.onChange} name="Stocked" />
</div>
<div className="form-group">
<label>Price </label>
<input type="text" onChange={this.onChange} name="Price" />
</div>
<button onClick={this.onSave}>Save</button>
</form>
</div>
);
}
}
export default AddHero;

Categories