How to pass props throught React components without using Redux - javascript

Sup guys!
Can I have some help to understood this assessment challenge? I've allready send it, but a horrible doubt keep bouncing on my head:
I was ordered to complete a simple React app, that loads user input in a component, and pass those data as props to another component, rendered from another one. Something like this:
function DataInput(){
const [input, setInput]=useState({
firstName:'',
lastName:'',
phone:'',
)}
function handleChange(e){
setInput({
...input,
[e.target.name]:e.targe.value;
)}
}
function handleSubmit(){
/* dunno if this function is usefull to something. Can't figure out how to pass props from
a child ( DataInput ) to another one ( ContactList)without using Redux to store a Global State.
*/
}
return(
<form>
<input
type="text"
name="firstName"
placeholder="First Name"
value={input.firstName}
onChange={handleChange}
/>
<input
type="text"
name="lastName"
placeholder="Last Name"
value={input.lasttName}
onChange={handleChange}
/>
<input
type="text"
name="phone"
placeholder="Phone Number"
value={input.phone}
onChange={handleChange}
/>
<button onClick={handleSubmit}>Add User</button>
</form>
)}
function ContactList(props){
return(
<div>
<label>{props.firstName}</label>
<label>{props.lastName}</label>
<label>{props.phone}</label>
</div>
)}
function App(){
render(){
<IngresoDatos />
<ContactList />
}
}
ReactDOM.render(<App/>, document.getElementById('root'))

Related

Can't convert input element to re-usable component in react js

I created a login form and now I want to convert my input fields to re- usable component. I created separate common input.jsx file. This is input.jsx file's code.
import React from "react";
const Input = ({ name, label, value, onChange }) => {
return (
<div className="form-group">
<label htmlFor={name}>{label}</label>
<input
value={value}
onChange={onChange}
id={name}
name={name}
type="text"
className="form-control"
/>
</div>
);
};
export default Input;
and imported it to my loginForm.jsx. Here is my loginForm.jsx render method
handleChange = ({ currentTarget: input }) => {
const account = { ...this.state.account };
account[input.name] = input.value;
this.setState({ account });
};
render() {
const { account } = this.state;
return (
<div>
<h1>Login</h1>
<form onSubmit={this.handleSubmit}>
<Input
name="username"
value={account.username}
label="Username"
onChange={this.handleChange}
/>
<Input
name="password"
value={account.password}
label="Password"
onChange={this.handleChange}
/>
<button className="btn btn-primary">Login</button>
</form>
</div>
);
}
But after adding below code to my loginForm.jsx,
<Input
name="username"
value={account.username}
label="Username"
onChange={this.handleChange}
/>
code and deleted previous code ,
<div className="form-group">
<label htmlFor="username">Username</label>
<input
value={account.username}
name="username"
onChange={this.handleChange}
ref={this.username}
id="username"
type="text"
className="form-control"
/>
</div>
suddenly my login page not loading.(Empty page).
My login page's console showing below error.
The above error occurred in the <LoginForm> component:
at LoginForm (http://localhost:3000/main.5d4e82bfe117bc198b43.hot-update.js:27:5)
at Route (http://localhost:3000/static/js/bundle.js:54444:5)
at Switch (http://localhost:3000/static/js/bundle.js:54739:5)
at main
at App
at Router (http://localhost:3000/static/js/bundle.js:54612:5)
at BrowserRouter (http://localhost:3000/static/js/bundle.js:53870:5)
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.

Create a reusable Form Input component with React & TypeScript

How can I define input attributes in typescript? I have an AddUser Component and TextInput Component, I want to import the TextInput component inside the AddUser component and then pass props to the TextInput component.
AddUser.tsx
import Button from '../Shared/Form/Button/Button';
import Form from '../Shared/Form/Form';
import TextArea from '../Shared/Form/TextArea/TextArea';
import TextInput from '../Shared/Form/TextInput/TextInput';
const AddUser = () => {
return (
<div>
<h1>Add User</h1>
<Form method="post" className={'user-form'}>
<TextInput label={'Name'} type="text" name="name" required />
<TextInput label={'Email'} type="email" name="email" required />
<TextInput label={'Country'} type="text" name="country" required />
<TextInput label={'Phone'} type="text" name="phone" required />
<TextArea label={'Address'} name="address" cols="30" rows="4" />
<div className="form-button">
<Button type={'submit'} className={'btn-add'}>
Add
</Button>
<Button type={'submit'} className={'btn-close'}>
Cancel
</Button>
</div>
</Form>
</div>
);
};
export default AddUser;
TextInput.tsx
const TextInput = ({ className, label, ...rest }: { className: string; label: string }) => {
return (
<div className={`${className} form-field`}>
<label htmlFor={label}>{label}</label>
<input {...rest} />
</div>
);
};
export default TextInput;
You can extend HTMLProps which comes with react:
import { HTMLProps } from "react";
interface MyCOmponentProps extends HTMLProps<HTMLInputElement> {
{...}
}
This is how we can make a reusable component. maybe I missed something in onChangeAction according to type script. please let me know me in the comment section so that i can help you better
Example codesandbox
const AddUser = () => {
return (
<div>
<h1>Add User</h1>
<form method="post" className={"user-form"}>
<TextInput
label={"Name"}
placeholder="Name"
type="text"
name="name"
required
/>
<TextInput
label={"Email"}
placeholder="Email"
type="email"
name="email"
required
/>
<TextInput
label={"Country"}
placeholder="Country"
type="text"
name="country"
required
/>
<TextInput
label={"Phone"}
placeholder="Phone"
type="text"
name="phone"
required
/>
</form>
</div>
);
};
export default AddUser;
const TextInput = ({
className,
label,
value,
type,
onChangeAction,
placeholder
}) => {
return (
<div className={`${className} form-field`}>
<label htmlFor={label}>{label}</label>
<input
placeholder={placeholder || "Text"}
type={type || "text"}
value={value}
onChange={onChangeAction}
/>
</div>
);
};

submit form in react with variable set of inputs?

//form.js
const form=({seg,onSubmit,onChange})=>{
<form id="input_form" onSubmit={onSubmit}>
{seg.map(item=>
<>
<input type="number" onChange={onChange} name={item}
type="number" required className="form-control control" id={item+1} />
</>
)}
</form>}
// app.js
state={array:[0.0,1.0], seg=3}
onSubmit=()=>{
}
onChange=()=>{
// should update the array(as this.state.array=[0.0, inputa,inputb,inputc..., 1.0])}
how do i update the array? what should be the onChange, onSubmit func?
(this.state.seg is variable).
You can use this.setState({ seg : newValue});
You can set the seg state property value like this
onChange=(event)=>{
this.setState({seg: event.target.value});
}
I suppose yo need to update the array with current seg value. If you want to do it using onSubmit, you have to use a button with type of submit. Then the button calls the onSubmit function. Try this.
<form id="input_form" onSubmit={onSubmit}>
{seg.map(item =>
<>
<input type="number" onChange={onChange} name={item} type="number" required className="form-control control" id={item + 1} />
<button type="submit">Submit</button>
</>
)}
</form>
onSubmit=()=>{
this.setState({
array: [...this.state.array, seg]
})
}

React.js submit button didn't work on Console Log?

when I click on the submit button on react js, Submit doesn't work, I don't know why?
I'm using ant.design Ui component in on backend Using Django python.
import React from "react";
import { Form, Input, Button } from "antd";
const FormItem = Form.Item;
class ExtrashiftForm extends React.Component {
handleFormSubmit = (event) => {
event.preventDefault();
const title = event.target.elements.title.value;
const manager = event.target.elements.manager.value;
const gender = event.target.elements.gender.value;
const Lable = event.target.elements.Lable.value;
const datetime = event.target.elements.datetime.value;
console.log(title, manager,gender,Lable,datetime);
};
render() {
return (
<div>
<Form onSubmit={this.handleFormSubmit}>
<FormItem name="title" label="Title">
<Input placeholder="title here" />
</FormItem>
<FormItem name="manager" label="Manager">
<Input placeholder="select Manager Name .. " />
</FormItem>
<FormItem name="gender" label="Gender">
<Input placeholder="select Gender Type .. " />
</FormItem>
<FormItem name="Lable" label="Lable">
<Input />
</FormItem>
<FormItem name="datetime" label="DateTime">
<Input />
</FormItem>
<FormItem>
<Button type="primary" htmlType="submit">
Ok
</Button>
</FormItem>
</Form>
</div>
);
}
}
export default ExtrashiftForm;
this part of code included inside the layout page, and all text coming but when I check Console in chrome browser, didn't send any data to console.
please help me, thank you
Change onSubmit to onFinish.
onFinish cb will have values as object. That also need to update.
<Form onFinish={(values) => console.log(values)}>
or
<Form onFinish={({title, manager,gender,Lable,datetime}) => console.log({title, manager,gender,Lable,datetime})}>
Try this one
<Form onFinish={(values) => this.handleFormSubmit(values)}>
<FormItem label="Title">
<Input placeholder="title here" name="title" />
</FormItem>
</Form>
const handleFormSubmit = (values) => {
const title = values.title;
console.log(title);
};

Semantic-UI-React: Form.Field is breaking layout

I'm working on a form to create a new product and I need a row with 3 equals fields but I'm not getting there using React Semantic Ui.
How can I code 3 equal input fields using react semantic ui?
That's what I've tried:
import { Form, Input, Button, TextArea, Header, Icon } from "semantic-ui-react";
function CreateProduct() {
return (
<>
<Header as="h2" block>
<Icon name="add square" color="violet" />
Cadastrar Produto
</Header>
<Form>
<Form.Group widths="equal">
<Form.Field
control={Input}
name="name"
label="Nome"
placeholder="Nome do Produto"
/>
<Form.Field
control={Input}
name="price"
label="Preço"
placeholder="Preço"
min="0.00"
step="0.10"
type="number"
/>
<Form.Field
control={Input}
name="media"
type="file"
label="Imagem"
accept="image/*"
content="Escolha Imagem"
/>
</Form.Group>
<Form.Field
control={TextArea}
name="description"
label="Descrição"
placeholder="Descrição do Produto"
/>
<Form.Field
control={Button}
inverted
color="violet"
icon="pencil alternate"
content="Cadastrar"
type="submit"
/>
</Form>
</>
);
}
export default CreateProduct;
The output that I am getting is:
See the 3rd input "Imagem"?
It seems that the field is not following the Form.Group props widths='equal' from semanctic-react-ui document
This layout is exceed because of the file type content.
May be you can try this way to get that layout
import React, { Component } from "react";
import { Form, Input, Button, TextArea } from "semantic-ui-react";
class FormExample extends Component {
fileInputRef = React.createRef();
render() {
return (
<Form>
<Form.Group widths="equal">
<Form.Field
control={Input}
name="name"
label="Nome"
placeholder="Nome do Produto"
/>
<Form.Field
control={Input}
name="price"
label="Preço"
placeholder="Preço"
min="0.00"
step="0.10"
type="number"
/>
<Form.Field>
<label>Imagem</label>
<Button
style={{ width: "100%" }}
content="Choose File"
labelPosition="left"
icon="file"
onClick={() => this.fileInputRef.current.click()}
/>
<input
ref={this.fileInputRef}
type="file"
hidden
onChange={this.fileChange}
/>
</Form.Field>
</Form.Group>
<Form.Field
control={TextArea}
name="description"
label="Descrição"
placeholder="Descrição do Produto"
/>
<Form.Field
control={Button}
inverted
color="violet"
icon="pencil alternate"
content="Cadastrar"
type="submit"
/>
</Form>
);
}
}
export default FormExample;
demo : https://codesandbox.io/s/zen-frost-9ihqw (adjust the screen size for full view)
I found a good solution just adding the "Fluid" props on the second .
<Form.Field
fluid
control={Input}
name="price"
label="Preço"
placeholder="Preço"
min="0.00"
step="0.10"
type="number"
/>

Categories

Resources