how do i pass values dynamically in react to form - javascript

I am learning react by myself, and I am having a hard time doing something thought it would be simple.
In summary, I have a menu with a few items.
I want to be able to select that menu item and when that happens, open a form next to it, the form has inputs, and those input will be prefilled in case there's a saved value for it.
I want, if possible, to hide the editable form in case I click away from the form.
I am not sure how to do that. I have been playing with the props, and react is complaining about uncontrollable and controllable components. I read about it and I get and. Now I am not sure what is the best way to do this. I don't need a "hack" in case my solution is not the right way to do it. I am really looking for how people would handle similar problem in an elegant way in React.
Here's parts of the code I was writing, using material-ui-next
class EditMenu extends React.Component {
constructor(props) {
super(props);
console.log(props);
const itemsInfo = [
{id: 11 ,
title: 'title 1',
description: 'desc 1'
},
{id: 22 ,
title: 'title 2',
description: 'desc 2'
},
{id: 33 ,
title: 'title 3',
description: 'desc 3'
},
];
let itemId = this.props.selectedItem;
let item = _.find(itemsInfo, {id:itemId});
this.state = {
value: '',
item: item,
itemName: '',
itemDescription: ''
};
}
handleitemNameSetting = (event) => {
event.preventDefault();
debugger;
this.setState({
itemName: event.target.value
});
}
render() {
return (
<div className="form-container">
<form >
<TextField
id="item-name"
label="item Name"
margin="normal"
onChange={this.handleItemNameSetting}
value={this.state.item.title}
/>
<br />
<TextField
id="dish-desc"
label="item Description"
margin="normal"
value={this.state.item.description}
/>
<br />
<TextField
className="value-field-container"
label="value"
type="number"
hinttext="item value" />
</form>
</div>
);
}
}
class MenuList extends React.Component {
state = { editMenuOpen: false };
handleClick = (id,event, item, ind) => {
this.setState({editMenuOpen: true, selectedItem: id});
};
render() {
const { classes } = this.props;
const menuItems = [
{id: 11 ,
title: 'title 1'
},
{id: 22 ,
title: 'title 2'
},
{id: 33 ,
title: 'title 3'
},
];
return (
<div className={classes.root}>
<Grid container spacing={24}>
<Grid item xs={2}>
<div>
<List
component="nav"
subheader={<ListSubheader component="div">Lunch Menu</ListSubheader>}
>
{menuItems.map(item => (
<ListItem button key={`${item.id}`} onClick= { () => this.handleClick(item.id)}>
<ListItemText primary={`${item.title}`} />
</ListItem>
))}
</List>
</div>
</Grid>
<Grid item xs>
<div>
{ this.state.editMenuOpen ? <EditMenu selectedItem={this.state.selectedItem}></EditMenu> : null }
</div>
</Grid>
</Grid>
</div>
);
}
}

I would add an onClick event handler on the outermost parent element, that triggers a setState and changes the editMenuOpen to false.
Let's assume it's called handleCloseMenuClick.
But i would also need to add an event handler on my form itself that stops the event from handleCloseMenuClick from triggering when i click my form using event.stopPropagation()
Check the console in this example and see the difference when you remove the event.stopPropagation()

Related

How do I select value and options (label names) are invisible from react-select dropdown?

I am new to React. I'm using react-select and I've used the following code. The dropdown is displayed but I'm unable to see names and unable to view after selecting.
<Select
variant="outlined"
margin="normal"
fullWidth
value={this.state.selected}
options={RewardAutomationsList}
name="selected"
onChange={this.handleChange}
placeholder='None'
>
{RewardAutomationsList.map((option) => (
<option key={option.id} value ={option.name} label={option.name}>
{option.name}
</option>
))}
</Select>
handleChange = event => {
this.setState({
selected: event.name
});
};
The RewardAutomationsList looks like this:
RewardAutomationsList:
0:{name: "TEST 1 (INR 100)", id: "123"}
1:{name: "test 2 (INR 250)", id: "456"}
Can someone help with this?
same npm package use like this block code.
import React, { Component } from 'react'
import Select from 'react-select'
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' }
]
const MyComponent = () => (
<Select options={options} />
)
react-select accepts an array of objects having label and value keys. Your option objects in RewardAutomationsList have id and name keys, so it can't be displayed. You need to change them.
Also, when you subscribe to change events with react-select's onChange prop, the callback function you provide receives the selectedOption, not the event.
The following should work:
const RewardAutomationsList = [
{ label: "TEST 1 (INR 100)", value: "123" },
{ label: "test 2 (INR 250)", value: "456" },
];
class App extends React.Component {
state = {
selected: null,
}
handleChange = (selectedOption) => {
this.setState({
selected: selectedOption,
});
};
render() {
return (
<React.Fragment>
<Select
fullWidth
margin="normal"
name="selected"
onChange={this.handleChange}
options={RewardAutomationsList}
placeholder="None"
value={this.state.selected}
variant="outlined"
/>
{/* It's not necessary and it's only here to show the current state */}
<pre>{JSON.stringify(this.state, null, 2)}</pre>
</React.Fragment>
);
}
}

Render a radio button as already selected on page load - React js

I have this component:
import React from 'react';
const options = [
{ label: "Lifestyle", value: "lifestyle"},
{ label: "Area", value: "area" },
{ label: "Random", value: "random" }
];
const ChannelCategory = props =>
props.visible ? (
<div>
{props.title}
<ul>
{options.map((option) => (
<li key={option.value}>
<label>
{option.label}
<input
className={props.className}
name={props.name} // need to be different
selected={props.selected === option.value} // e.g. lifestyle === lifestyle
onChange={() => props.onChange(option.value)}
type="radio"
/>
</label>
</li>
))}
</ul>
</div>
) : null;
export default ChannelCategory;
I am rendering it on another page here in a .map:
let displayExistingChannels = null;
if (channels !== null){
displayExistingChannels = (
channels.map(channel => {
return (
<Grid key={channel.key} item style={styles.gridItem} justify="space-between">
<ChannelListItem
channel={channel}
isSaving={isSaving}
onDeleteChannelClick={onDeleteChannelClick}
key={channel.key}
onFormControlChange={onFormControlChange}
onUndoChannelClick={onUndoChannelClick}
/>
{channel.category}
<ChannelCategory
visible={true}
onChange={value => setCategoryName(value)}
title="Edit Category"
selected={channel.category}
name={channel.key} // unique for every channel
/>
</Grid>
)
})
)
}
I am using fake data for the map:
const fakeChannelData = setupChannels(
[{id: "2f469", name: "shopping ", readOnly: false, category: "lifestyle"},
{id: "bae96", name: "public", readOnly: true, category: "null"},
{id: "06ea6", name: "swimming ", readOnly: false, category: "sport"},
{id: "7e2bb", name: "comedy shows ", readOnly: false, category: "entertainment"}]);
const [channels, setChannels] = useState(fakeChannelData);
Please can someone tell me why when I add selected={channel.category} in my .map function it does not show the selected category preselected on the FE on page load? Not sure where I have gone wrong? Thanks!
checked is the correct attribute to use for input tag, not selected.
<input
...
checked={props.selected === option.value}
...
/>
ref: https://developer.mozilla.org/fr/docs/Web/HTML/Element/Input/radio

Use variable in .map function react

I am a new reacter. I have a problem when i use map and variables could you help me?
i don't know how to input the variables in options like value={name.value}
const info = [
{ key: "닉네임", value: "name" },
{ key: "지역", value: "area" },
{ key: "생일", value: "birthday" },
{ key: "키", value: "tall" },
{ key: "몸매", value: "body" },
{ key: "직업", value: "job" },
{ key: "회사", value: "company" },
{ key: "학교", value: "school" },
{ key: "학력", value: "background" },
{ key: "종교", value: "religion" },
{ key: "흡연", value: "smoking" },
{ key: "카카오 아이디", value: "kakaoid" }
];
<Grid container spacing={3}>
{info.map((info, index) => (
<Grid item xs={12} sm={6} key={index}>
<TextField
required
id={index}
name={info.value}
label={info.key}
value={}
onChange={}
fullWidth
/>
</Grid>
))}
</Grid>
I want to make it like that
<Grid item xs={12} sm={6} key={1}>
<TextField
required
id={1}
name={"name"}
label={"닉네임"}
value={name.value}
onChange={name.onChange}
fullWidth
/>
</Grid>
If you want to set the value for the each text field .
Define a state variable for each of the text-field (use name of the each text fields)and bind an on-change event.
In on-change bind an this and get the name & value , based on on-change set the value to the name state for each text field
Now pass the state to each of the text-field .
You should aware of state an props in react , on-change events.
For example
constructor(props){
super(props);
this.state = {
value:''
}
}
inputchange = (event) =>{
this.setState({
value:event.target.value
})
}
render(){
return (
<div className="todolist">
<input type="text" value={this.state.value} onChange={this.inputchange}/>
<input type="button" value="Submit" onClick={this.props.handleclick.bind(this,this.state.value)}/>
</div>
);
}
}

Unable to pass props to child component in react

I'm still getting to grips with react but I can't see why this isn't working, it should be passing the props from tabs into <Tab /> and outputting the button each time.
If I put no text next to {this.props.content} it doesn't display anything, if I put testText next to {this.props.content} it will output the button 5 times but only display testText not the name field it should be displaying via the content={item.name} prop
class TopCategories extends React.Component {
render() {
const Tab = () => (
<TestBtn key={this.props.key} >
testText {this.props.content}
</TestBtn>
)
const items = [
{ id: 1, name: 'tab-1', text: 'text' },
{ id: 2, name: 'tab-2', text: 'text' },
{ id: 3, name: 'tab-3', text: 'text' },
{ id: 4, name: 'tab-4', text: 'text' },
{ id: 5, name: 'tab-5', text: 'text' },
]
const tabs = items.map(item =>
<Tab key={item.id} content={item.name} />,
)
return (
<Container>
<Wrapper>
{tabs}
</Wrapper>
</Container>
)
}
}
export default TopCategories
You need to pass props to the stateless function and since it's a stateless component, this is not available. It should be something like:
const Tab = (props) => {
return (
<TestBtn key={props.key} >
testText {props.content}
</TestBtn>
);
}

How get data from material-ui TextField, DropDownMenu components?

I create form, I have several TextField, DropDownMenu material-ui components included, question is how I can collect all data from all TextFields, DropDownMenus in one obj and sent it on server. For TextField it has TextField.getValue() Returns the value of the input. But I can`t understand how to use it.
var React = require('react'),
mui = require('material-ui'),
Paper = mui.Paper,
Toolbar = mui.Toolbar,
ToolbarGroup = mui.ToolbarGroup,
DropDownMenu = mui.DropDownMenu,
TextField = mui.TextField,
FlatButton = mui.FlatButton,
Snackbar = mui.Snackbar;
var menuItemsIwant = [
{ payload: '1', text: '[Select a finacial purpose]' },
{ payload: '2', text: 'Every Night' },
{ payload: '3', text: 'Weeknights' },
{ payload: '4', text: 'Weekends' },
{ payload: '5', text: 'Weekly' }
];
var menuItemsIcan = [
{ payload: '1', text: '[Select an objective]' },
{ payload: '2', text: 'Every Night' },
{ payload: '3', text: 'Weeknights' },
{ payload: '4', text: 'Weekends' },
{ payload: '5', text: 'Weekly' }
];
var menuItemsHousing = [
{ payload: '1', text: '[Select housing]' },
{ payload: '2', text: 'Every Night' },
{ payload: '3', text: 'Weeknights' },
{ payload: '4', text: 'Weekends' },
{ payload: '5', text: 'Weekly' }
];
var menuItemsIlive = [
{ payload: '1', text: '[Select family mambers]' },
{ payload: '2', text: 'Every Night' },
{ payload: '3', text: 'Weeknights' },
{ payload: '4', text: 'Weekends' },
{ payload: '5', text: 'Weekly' }
];
var menuItemsLifestyle = [
{ payload: '1', text: '[Select lifestyle]' },
{ payload: '2', text: 'Every Night' },
{ payload: '3', text: 'Weeknights' },
{ payload: '4', text: 'Weekends' },
{ payload: '5', text: 'Weekly' }
];
var menuItemsLifestyle2 = [
{ payload: '1', text: '[Select savings]' },
{ payload: '2', text: 'Every Night' },
{ payload: '3', text: 'Weeknights' },
{ payload: '4', text: 'Weekends' },
{ payload: '5', text: 'Weekly' }
];
var menuItemsIncome = [
{ payload: '1', text: '[Select your yearly income]' },
{ payload: '2', text: 'Every Night' },
{ payload: '3', text: 'Weeknights' },
{ payload: '4', text: 'Weekends' },
{ payload: '5', text: 'Weekly' }
];
var Content = React.createClass({
getInitialState: function() {
return {
//formData: {
// name: '',
// age: '',
// city: '',
// state: ''
//},
errorTextName: '',
errorTextAge: '',
errorTextCity: '',
errorTextState: ''
};
},
render: function() {
return (
<div className="container-fluid">
<div className="row color-bg"></div>
<div className="row main-bg">
<div className="container">
<div className="mui-app-content-canvas page-with-nav">
<div className="page-with-nav-content">
<Paper zDepth={1}>
<h2 className="title-h2">Now, what would you like to do?</h2>
<Toolbar>
<ToolbarGroup key={1} float="right">
<span>I want to</span>
<DropDownMenu
className="dropdown-long"
menuItems={menuItemsIwant}
//autoWidth={false}
/>
</ToolbarGroup>
</Toolbar>
<div className="clearfix"></div>
<Toolbar>
<ToolbarGroup key={2} float="right">
<span>So I can</span>
<DropDownMenu
className="dropdown-long"
menuItems={menuItemsIcan}
//autoWidth={false}
/>
</ToolbarGroup>
</Toolbar>
<h2 className="title-h2">Please, share a little about you.</h2>
<div className="clearfix"></div>
<Toolbar>
<ToolbarGroup key={3} float="right">
<span>I am</span>
<TextField
id="name"
className="text-field-long"
ref="textfield"
hintText="Full name"
errorText={this.state.errorTextName}
onChange={this._handleErrorInputChange}
/>
<span>and I am</span>
<TextField
id="age"
className="text-field-short"
ref="textfield"
hintText="00"
errorText={this.state.errorTextAge}
onChange={this._handleErrorInputChange}
/>
<span className="span-right-measure">years of age.</span>
</ToolbarGroup>
</Toolbar>
<div className="clearfix"></div>
<Toolbar>
<ToolbarGroup key={4} float="right">
<span>I</span>
<DropDownMenu
hintText="I"
menuItems={menuItemsHousing}
//autoWidth={false}
/>
<span>in</span>
<TextField
id="city"
ref="textfield"
className="text-field-long"
hintText="City"
errorText={this.state.errorTextCity}
onChange={this._handleErrorInputChange}
/>
<span>,</span>
<TextField
id="state"
ref="textfield"
className="text-field-short text-field-right-measure"
hintText="ST"
errorText={this.state.errorTextState}
onChange={this._handleErrorInputChange}
/>
</ToolbarGroup>
</Toolbar>
<div className="clearfix"></div>
<Toolbar>
<ToolbarGroup key={5} float="right">
<span>Where I live</span>
<DropDownMenu
className="dropdown-long"
menuItems={menuItemsIlive}
//autoWidth={false}
/>
</ToolbarGroup>
</Toolbar>
<div className="clearfix"></div>
<Toolbar>
<ToolbarGroup key={6} float="right">
<span>My lifestyle is</span>
<DropDownMenu
className="dropdown-short"
menuItems={menuItemsLifestyle}
//autoWidth={false}
/>
<span>and I've saved</span>
<DropDownMenu
className="dropdown-short"
menuItems={menuItemsLifestyle2}
//autoWidth={false}
/>
</ToolbarGroup>
</Toolbar>
<div className="clearfix"></div>
<Toolbar>
<ToolbarGroup key={7} float="right">
<span>My yearly household is about</span>
<DropDownMenu
className="dropdown-mobile"
menuItems={menuItemsIncome}
//autoWidth={false}
/>
</ToolbarGroup>
</Toolbar>
<div className="clearfix"></div>
<div className="button-place">
<FlatButton
onTouchTap={this._handleClick}
label="I'm done lets go!"
/>
<Snackbar
ref="snackbar"
message="Invalid input, please check and try again"
/>
</div>
</Paper>
</div>
</div>
</div>
</div>
</div>
);
},
_handleErrorInputChange: function(e) {
if (e.target.id === 'name') {
var name = e.target.value;
this.setState({
//name: name,
errorTextName: e.target.value ? '' : 'Please, type your Name'
});
} else if (e.target.id === 'age') {
var age = e.target.value;
this.setState({
//age: age,
errorTextAge: e.target.value ? '' : 'Check Age'
});
} else if (e.target.id === 'city') {
var city = e.target.value;
this.setState({
//city: city,
errorTextCity: e.target.value ? '' : 'Type City'
});
} else if (e.target.id === 'state') {
var state = e.target.value;
this.setState({
//state: state,
errorTextState: e.target.value ? '' : 'Type State'
});
}
},
_handleClick: function(e) {
this.refs.snackbar.show();
//TODO: find a way to change errorText for all empty TextField
if (this.refs.textfield && this.refs.textfield.getValue().length === 0) {
this.setState({
errorTextState: 'Type State',
errorTextCity: 'Type City',
errorTextAge: 'Check Age',
errorTextName: 'Please, type your Name'
});
}
}
});
module.exports = Content;
I want sent it on server in _handleClick method.
Add an onChange handler to each of your TextField and DropDownMenu elements. When it is called, save the new value of these inputs in the state of your Content component. In render, retrieve these values from state and pass them as the value prop. See Controlled Components.
var Content = React.createClass({
getInitialState: function() {
return {
textFieldValue: ''
};
},
_handleTextFieldChange: function(e) {
this.setState({
textFieldValue: e.target.value
});
},
render: function() {
return (
<div>
<TextField value={this.state.textFieldValue} onChange={this._handleTextFieldChange} />
</div>
)
}
});
Now all you have to do in your _handleClick method is retrieve the values of all your inputs from this.state and send them to the server.
You can also use the React.addons.LinkedStateMixin to make this process easier. See Two-Way Binding Helpers. The previous code becomes:
var Content = React.createClass({
mixins: [React.addons.LinkedStateMixin],
getInitialState: function() {
return {
textFieldValue: ''
};
},
render: function() {
return (
<div>
<TextField valueLink={this.linkState('textFieldValue')} />
</div>
)
}
});
Here all solutions are based on Class Component,
but i guess most of the people who learned React recently (like me),
at this time using functional Component.
So here is the solution based on functional component.
Using useRef hooks of ReactJs and inputRef property of TextField.
import React, { useRef, Component } from 'react'
import { TextField, Button } from '#material-ui/core'
import SendIcon from '#material-ui/icons/Send'
export default function MultilineTextFields() {
const valueRef = useRef('') //creating a refernce for TextField Component
const sendValue = () => {
return console.log(valueRef.current.value) //on clicking button accesing current value of TextField and outputing it to console
}
return (
<form noValidate autoComplete='off'>
<div>
<TextField
id='outlined-textarea'
label='Content'
placeholder='Write your thoughts'
multiline
variant='outlined'
rows={20}
inputRef={valueRef} //connecting inputRef property of TextField to the valueRef
/>
<Button
variant='contained'
color='primary'
size='small'
endIcon={<SendIcon />}
onClick={sendValue}
>
Send
</Button>
</div>
</form>
)
}
Try this,
import React from 'react';
import {useState} from 'react';
import TextField from '#material-ui/core/TextField';
const Input = () => {
const [textInput, setTextInput] = useState('');
const handleTextInputChange = event => {
setTextInput(event.target.value);
};
return(
<TextField
label="Text Input"
value= {textInput}
onChange= {handleTextInputChange}
/>
);
}
export default Input;
Explanation if the above code was not clear.
First we create a state to store the text input called textInput and assign it the value ''.
Then we return a material UI <TextField /> component whose value attribute is set to the textInput state. Doing this we display the current value of the textInput in the <TextField />. Any changes to the value of textInput will change the value attribute of the <TextField />, courtesy of React.
Then we use the onChange attribute of <TextField /> to run a handler function every time the value of the <TextField /> value attribute changes. This handler function is an arrow function stored in the constant handleTextInputChange. It takes an event as an argument. When the onChange attribute runs the handler function, it sends the event as an argument to the handler function.
The value of the <TextField /> is stored in event.target.value. We then use the setTextInput method of the state to set the state to the value attribute of the <TextField />. Thus this change is reflected in the <TextField /> whose value attribute is the value of the textInput state.
Thus the data input into the <TextField /> is stored in the state textInput, ready to be used when required.
flson's code did not work for me. For those in the similar situation, here is my slightly different code:
<TextField ref='myTextField'/>
get its value using
this.refs.myTextField.input.value
The strategy of the accepted answer is correct, but here's a generalized example that works with the current version of React and Material-UI.
The flow of data should be one-way:
the initialState is initialized in the constructor of the MyForm control
the TextAreas are populated from this initial state
changes to the TextAreas are propagated to the state via the handleChange callback.
the state is accessed from the onClick callback---right now it just writes to the console. If you want to add validation it could go there.
import * as React from "react";
import TextField from "material-ui/TextField";
import RaisedButton from "material-ui/RaisedButton";
const initialState = {
error: null, // you could put error messages here if you wanted
person: {
firstname: "",
lastname: ""
}
};
export class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = initialState;
// make sure the "this" variable keeps its scope
this.handleChange = this.handleChange.bind(this);
this.onClick = this.onClick.bind(this);
}
render() {
return (
<div>
<div>{this.state.error}</div>
<div>
<TextField
name="firstname"
value={this.state.person.firstname}
floatingLabelText="First Name"
onChange={this.handleChange}/>
<TextField
name="lastname"
value={this.state.person.lastname}
floatingLabelText="Last Name"
onChange={this.handleChange}/>
</div>
<div>
<RaisedButton onClick={this.onClick} label="Submit!" />
</div>
</div>
);
}
onClick() {
console.log("when clicking, the form data is:");
console.log(this.state.person);
}
handleChange(event, newValue): void {
event.persist(); // allow native event access (see: https://facebook.github.io/react/docs/events.html)
// give react a function to set the state asynchronously.
// here it's using the "name" value set on the TextField
// to set state.person.[firstname|lastname].
this.setState((state) => state.person[event.target.name] = newValue);
}
}
React.render(<MyForm />, document.getElementById('app'));
(Note: You may want to write one handleChange callback per MUI Component to eliminate that ugly event.persist() call.)
In 2020 for TextField, via functional components:
const Content = () => {
...
const textFieldRef = useRef();
const readTextFieldValue = () => {
console.log(textFieldRef.current.value)
}
...
return(
...
<TextField
id="myTextField"
label="Text Field"
variant="outlined"
inputRef={textFieldRef}
/>
...
)
}
Note that this isn't complete code.
Faced to this issue after a long time since question asked here. when checking material-ui code I found it's now accessible through inputRef property.
...
<CssTextField
inputRef={(c) => {this.myRefs.username = c}}
label="Username"
placeholder="xxxxxxx"
margin="normal"
className={classes.textField}
variant="outlined"
fullWidth
/>
...
Then Access value like this.
onSaveUser = () => {
console.log('Saving user');
console.log(this.myRefs.username.value);
}
Here's the simplest solution i came up with, we get the value of the input created by material-ui textField :
create(e) {
e.preventDefault();
let name = this.refs.name.input.value;
alert(name);
}
constructor(){
super();
this.create = this.create.bind(this);
}
render() {
return (
<form>
<TextField ref="name" hintText="" floatingLabelText="Your name" /><br/>
<RaisedButton label="Create" onClick={this.create} primary={true} />
</form>
)}
hope this helps.
I don't know about y'all but for my own lazy purposes I just got the text fields from 'document' by ID and set the values as parameters to my back-end JS function:
//index.js
<TextField
id="field1"
...
/>
<TextField
id="field2"
...
/>
<Button
...
onClick={() => { printIt(document.getElementById('field1').value,
document.getElementById('field2').value)
}}>
//printIt.js
export function printIt(text1, text2) {
console.log('on button clicked');
alert(text1);
alert(text2);
};
It works just fine.
class Content extends React.Component {
render() {
return (
<TextField ref={(input) => this.input = input} />
);
}
_doSomethingWithData() {
let inputValue = this.input.getValue();
}
}

Categories