Get an array of data when saving in ReactJs - javascript

I have a form in reactjs application where I render some radio buttons.
const items = [
{
id: 1,
car: "BMW",
colors: [
{
id: 1,
text: "red"
},
{
id: 2,
text: "blue"
}
]
},
{
id: 2,
car: "Audi",
colors: [
{
id: 1,
text: "green"
},
{
id: 2,
text: "white"
}
]
}
];
const Demo = () => {
const onFinish = (values) => {
console.log("Success:", values);
};
const onFinishFailed = (errorInfo) => {
console.log("Failed:", errorInfo);
};
return (
<Form
{...layout}
name="basic"
initialValues={{
remember: true
}}
onFinish={onFinish}
onFinishFailed={onFinishFailed}
>
{items.map((i) => {
return (
<Form.Item
label={i.car}
key={i.car}
name={"carId" + i.id}
rules={[{ required: true, message: "Please" }]}
>
<Radio.Group>
{i.colors.map((color) => {
return (
<Radio key={color.text} value={color.text}>
{color.text}
</Radio>
);
})}
</Radio.Group>
</Form.Item>
);
})}
<Form.Item {...tailLayout}>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</Form>
);
};
Now when I save data I get:
{
carId1: "red",
carId2: "white"
}
Issue: I want to get data after saving in this way:
[
{
carId: 1,
colors: ["red"]
},
{
carId: 2,
colors: ["white"]
}
]
Question: How to get the same structure that I described above after saving the form?
demo: https://codesandbox.io/s/basic-usage-antd4102-forked-o3to7?file=/index.js:320-1730

I've added a link in comments with a simple data restructure solution, here
in case of it's not opening,
I've just updated the onFinish method to be:
const onFinish = (values) => {
const results = [];
items.forEach((carItem) => {
results.push({
carId: carItem.id,
colors: [values["carId" + carItem.id]]
});
});
console.log("Success:", results);
};
so you have the needed data and can structure it in any shape you want.

Related

react native (type script) : Selecting the father sons check box in flatlist

My goal is that when user select a checkbox of one of the fathers ('Non Veg Biryanis','Pizzas','Drinks','Deserts') in the flatlist, then those sons who belong to him are also selected.
When the check box is removed from all the children belonging to the same father, then the check box is also removed for the father as well.
this is my example (but its not works as can see, the father 'Pizzas' not checked but his sons checked)
The data is:
[
{
title: 'Non Veg Biryanis',
checked: false,
data: [
{ key: 'chicken', value: false, checked: false },
{ key: 'meat', value: false, checked: false },
{ key: 'veg', value: false, checked: false },
],
},
{
title: 'Pizzas',
checked: false,
data: [
{ key: 'olives', value: false, checked: false },
{ key: 'green cheese', value: false, checked: false },
{ key: 'paprika', value: false, checked: false },
],
},
{
title: 'Drinks',
checked: false,
data: [
{ key: 'cola', value: false, checked: false },
{ key: 'sprite', value: false, checked: false },
{ key: 'orange', value: false, checked: false },
],
},
{
title: 'Deserts',
checked: false,
data: [
{ key: 'cake', value: false, checked: false },
{ key: 'ice-cream', value: false, checked: false },
{ key: 'pie', value: false, checked: false },
],
},
]
The Accordian:
import React, { useState } from 'react';
import { View, TouchableOpacity, Text, FlatList, LayoutAnimation, Platform, UIManager } from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import styles from './AccordianStyle';
const Accordian = props => {
const [data, setData] = useState(props.item);
const [expanded, setExpanded] = useState(false);
if (Platform.OS === 'android') {
UIManager.setLayoutAnimationEnabledExperimental(true);
}
const onClick = (index: number) => {
console.log(data);
const temp = { ...data };
temp.data[index].checked = !temp.data[index].checked;
setData(temp);
};
const onClickFather = () => {
const temp = { ...data };
temp.checked = !temp.checked;
if (temp.checked) {
temp.data = temp.data.map((item: { checked: boolean }) => {
item.checked = true;
});
}
console.log(temp);
setData(temp);
};
const toggleExpand = () => {
LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
setExpanded(!expanded);
};
return (
<View>
<View style={styles.row}>
<TouchableOpacity onPress={() => onClickFather()}>
<Icon name={'check-circle'} size={24} color={data.checked ? 'green' : '#d3d7de'} />
</TouchableOpacity>
<Text style={[styles.title]}>{data.title}</Text>
<TouchableOpacity style={styles.row} onPress={() => toggleExpand()}>
<Icon name={expanded ? 'keyboard-arrow-up' : 'keyboard-arrow-down'} size={30} color={'grey'} />
</TouchableOpacity>
</View>
<View style={styles.parentHr} />
{expanded && (
<View style={{}}>
<FlatList
data={data.data}
numColumns={1}
scrollEnabled={false}
renderItem={({ item, index }) => (
<View>
<TouchableOpacity
style={[styles.childRow, styles.button, item.checked ? styles.btnActive : styles.btnInActive]}
onPress={() => onClick(index)}
>
<Text style={[styles.itemInActive]}>{item.key}</Text>
<Icon name={'check-circle'} size={24} color={item.checked ? 'green' : '#d3d7de'} />
</TouchableOpacity>
<View style={styles.childHr} />
</View>
)}
/>
</View>
)}
</View>
);
};
export default Accordian;
Modify your onClick function so that it loops through each entry in the data array with the some() method and check if any of the children (sons) are clicked.
If one of them is, then update set the checked property accordingly.
const onClick = (index: number) => {
setData(prevState => {
const newData = prevState.data.map((entry, entryIndex) =>
index === entryIndex ?
({ ...entry, checked: !entry.checked }) :
entry
);
const isAnyChildChecked = newData.some(({ checked }) =>
checked === true
);
return ({
...prevState,
checked: isAnyChildChecked,
data: newData
})
});
};
If the parent is clicked, then check or uncheck all the children as well.
const onClickFather = () => {
setData(prevState => {
const isParentChecked = !prevState.checked;
return ({
...prevState,
checked: isParentChecked,
data: prevState.data.map(item => ({ ...item, checked: isParentChecked }))
});
});
};

How can I change the color of material-table icons of onRowAdd, onRowUpdate, onRowDelete?

I tried to the material-table the library for basic crud operation. By using onRowAdd, onRowUpdate, onRowDelete, I get the icons for the same but I would like to know that how can I change the color of each of these three icons?
You can see my table has few icons and I am focusing on add, edit, delete icons I want to change color of these icons.
Here is the link to my codesandbox.
App.js file
import React, { useState } from 'react';
import './App.css';
import MaterialTable from 'material-table'
const empList = [
{ id: 1, name: "Neeraj", email: 'neeraj#gmail.com', phone: 9876543210, city: "Bangalore" },
{ id: 2, name: "Raj", email: 'raj#gmail.com', phone: 9812345678, city: "Chennai" },
{ id: 3, name: "David", email: 'david342#gmail.com', phone: 7896536289, city: "Jaipur" },
{ id: 4, name: "Vikas", email: 'vikas75#gmail.com', phone: 9087654321, city: "Hyderabad" },
]
function App() {
const [data, setData] = useState(empList)
const columns = [
{ title: "ID", field: "id", editable: false },
{ title: "Name", field: "name" },
{ title: "Email", field: "email" },
{ title: "Phone Number", field: 'phone', },
{ title: "City", field: "city", }
]
return (
<div className="App">
<h1 align="center">React-App</h1>
<h4 align='center'>Material Table with CRUD operation</h4>
<MaterialTable
title="Employee Data"
data={data}
columns={columns}
editable={{
onRowAdd: (newRow) => new Promise((resolve, reject) => {
const updatedRows = [...data, { id: Math.floor(Math.random() * 100), ...newRow }]
setTimeout(() => {
setData(updatedRows)
resolve()
}, 2000)
}),
onRowDelete: selectedRow => new Promise((resolve, reject) => {
const index = selectedRow.tableData.id;
const updatedRows = [...data]
updatedRows.splice(index, 1)
setTimeout(() => {
setData(updatedRows)
resolve()
}, 2000)
}),
onRowUpdate:(updatedRow,oldRow)=>new Promise((resolve,reject)=>{
const index=oldRow.tableData.id;
const updatedRows=[...data]
updatedRows[index]=updatedRow
setTimeout(() => {
setData(updatedRows)
resolve()
}, 2000)
})
}}
options={{
actionsColumnIndex: -1, addRowPosition: "first"
}}
/>
</div>
);
}
export default App;
You can override the icons and provide custom styles by setting the icons props. It accepts an object where the key is a type of operation (Add, Edit, Delete,...) and the value is an icon component. For reference, see the all-props section here.
<MaterialTable
{...props}
icons={{
Edit: () => <EditIcon style={{ color: "orange" }} />,
Delete: () => <DeleteIcon style={{ color: "red" }} />
}}
>
Live Demo
It's Simple. Inspect on the page and Select the Icon and Copy its style Name in Styles Tab.
Now, Go to App.css file and Create New Style with the icon style name shown on Inspect-styles area and there you can enter your desired color.
It will work.
In your App.css File,
Add below code
.MuiIconButton-colorInherit {
color: red;
}
change to any color

Read and save WP post meta field data from Gutenberg block

I used the code from this article as an example.
It is possible to read the data, but not to save it.
Code:
const { Component, Fragment } = wp.element;
const {
RichText,
InspectorControls,
PanelColorSettings,
AlignmentToolbar,
BlockControls,
} = wp.editor;
const { Button, PanelBody, SelectControl, TextControl } = wp.components;
const { __ } = wp.i18n;
const { registerBlockType } = wp.blocks;
const { withSelect, withDispatch } = wp.data;
class Inspector extends Component {
constructor(props) {
super(...arguments);
}
render() {
const backgroundColors = [
{ color: "#525252", name: "Черный" },
{ color: "#872d2d", name: "Акцентный красный" },
{ color: "#e49312", name: "Акцентный желтый" },
{ color: "#bab3a6", name: "Акцентный кремовый" },
];
const fontSizeOptions = [
{ value: "14px", label: __("14px") },
{ value: "16px", label: __("16px") },
{ value: "18px", label: __("18px") },
{ value: "22px", label: __("22px") },
{ value: "28px", label: __("28px") },
];
const paddingTopOptions = [
{ value: "0px", label: __("0px") },
{ value: "10px", label: __("10px") },
{ value: "25px", label: __("25px") },
{ value: "50px", label: __("50px") },
];
const paddingBottomOptions = [
{ value: "0px", label: __("0px") },
{ value: "10px", label: __("10px") },
{ value: "25px", label: __("25px") },
{ value: "50px", label: __("50px") },
];
const {
setAttributes,
attributes: { text_color, font_size, padding_top, padding_bottom },
} = this.props;
let PluginMetaFields = (props) => {
return (
<>
<TextControl
value={props.text_metafield}
label={__("Text Meta", "textdomain")}
onChange={(value) => props.onMetaFieldChange(value)}
/>
</>
);
};
PluginMetaFields = withSelect((select) => {
return {
text_metafield: select("core/editor").getEditedPostAttribute("meta")[
"_myprefix_text_metafield"
],
};
})(PluginMetaFields);
PluginMetaFields = withDispatch((dispatch) => {
return {
onMetaFieldChange: (value) => {
dispatch("core/editor").editPost({
meta: { _myprefix_text_metafield: value },
});
},
};
})(PluginMetaFields);
return (
<InspectorControls key="inspector">
<PanelBody title={__("Настройки абзаца")}>
<PanelColorSettings
title={__("Цвет шрифта")}
initialOpen={true}
colorSettings={[
{
value: text_color,
colors: backgroundColors,
onChange: (value) => setAttributes({ text_color: value }),
label: __("Цвет шрифта"),
},
]}
/>
<SelectControl
label={__("Размер шрифта")}
options={fontSizeOptions}
value={font_size}
onChange={(value) => this.props.setAttributes({ font_size: value })}
/>
<SelectControl
label={__("Отступ сверху")}
options={paddingTopOptions}
value={padding_top}
onChange={(value) =>
this.props.setAttributes({ padding_top: value })
}
/>
<SelectControl
label={__("Отступ снизу")}
options={paddingBottomOptions}
value={padding_bottom}
onChange={(value) =>
this.props.setAttributes({ padding_bottom: value })
}
/>
<PluginMetaFields />
</PanelBody>
</InspectorControls>
);
}
}
class HeadlineBlock extends Component {
render() {
const {
attributes: {
headline,
text_color,
font_size,
padding_top,
padding_bottom,
alignment,
},
setAttributes,
} = this.props;
const onChangeAlignment = (newAlignment) => {
this.props.setAttributes({
alignment: newAlignment === undefined ? "none" : newAlignment,
});
};
return [
<Inspector {...{ setAttributes, ...this.props }} />,
<div>
{
<BlockControls>
<AlignmentToolbar value={alignment} onChange={onChangeAlignment} />
</BlockControls>
}
<RichText
tagName="p"
placeholder={__("Текст...")}
keepPlaceholderOnFocus
value={headline}
formattingControls={["bold", "italic", "strikethrough", "link"]}
className={"font-" + font_size + " post-desc__p-text"}
style={{
color: text_color,
textAlign: alignment,
}}
onChange={(value) => setAttributes({ headline: value })}
/>
</div>,
];
}
}
registerBlockType("amm-custom-block/test-block", {
title: __("Тест блок"),
icon: "shield",
category: "AMM",
attributes: {
headline: {
type: "string",
},
alignment: {
type: "string",
default: "none",
},
text_color: {
type: "string",
default: "#525252",
},
font_size: {
type: "string",
default: "14px",
},
padding_top: {
type: "string",
default: "50px",
},
padding_bottom: {
type: "string",
default: "0px",
},
},
edit: HeadlineBlock,
save: function (props) {
const {
attributes: {
headline,
text_color,
font_size,
padding_top,
padding_bottom,
alignment,
},
} = props;
return (
<Fragment>
{headline && !!headline.length && (
<RichText.Content
tagName="p"
className={"font-" + font_size + " post-desc__p-text"}
style={{
color: text_color,
paddingTop: padding_top,
paddingBottom: padding_bottom,
textAlign: alignment,
}}
value={headline}
/>
)}
</Fragment>
);
},
});
So far just added a text field to the block and am trying to read and save the data.
With reading everything is OK, but saving the data does not work and there are no errors.
Any idea why this is happening?
sorry english is not a native language
The meta field _myprefix_text_metafield is a protected field as it starts with a "_" (underscore). This is why you can read the value in withSelect() but not save over it withDispatch() without passing auth_callback.
To save to a protected field, the auth_callback is required, eg:
<?php
register_post_meta( 'post', '_myprefix_text_metafield', array(
'show_in_rest' => true,
'single' => true,
'type' => 'string',
'auth_callback' => function() {
return current_user_can( 'edit_posts' );
})
);
?>
There is an example in the tutorial you are following:
https://css-tricks.com/managing-wordpress-metadata-in-gutenberg-using-a-sidebar-plugin/#post-291605
Alternatively, if your meta field is not required to be protected/private: re-register your meta field as myprefix_text_metafield (no underscore in the name and no auth_callback) and your current code will work, eg:
<?php
register_post_meta( 'post', 'myprefix_text_metafield', array(
'show_in_rest' => true,
'single' => true,
'type' => 'string'
);
?>

Save data in a specific way

I have an application where user have to input data about it and after saving that form, the data should be outputed in a certain form.
const ParrentForm = () => {
const [carNr, setCarNr] = useState([]);
const onFinish = (values) => {
const { firstName, lastName } = values;
const user = {
firstName,
lastName,
things: {
cars: []
}
};
console.log(user);
};
const onFinishFailed = (errorInfo) => {
console.log("Failed:", errorInfo);
};
const setFloorsNrHandler = (nr) => {
setCarNr(Array.from({ length: nr }, (v, k) => k));
};
return (
<div>
<Form
name="main"
initialValues={{ remember: true }}
onFinish={onFinish}
onFinishFailed={onFinishFailed}
>
<Form.Item
label="First Name"
name="firstName"
rules={[{ required: true, message: "Please input your first name!" }]}
>
<Input />
</Form.Item>
<Form.Item
label="Last Name"
name="lastName"
rules={[{ required: true, message: "Please input your last name!" }]}
>
<Input />
</Form.Item>
<Form.Item
name="nrOfCars"
label="Cars"
rules={[{ type: "number", min: 0, max: 15 }]}
>
<InputNumber onChange={setFloorsNrHandler} />
</Form.Item>
{carNr.map((f, k) => {
return (
<Form.Item key={k}>
<InnerForm cKey={k} />
</Form.Item>
);
})}
<Form.Item>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</Form>
</div>
);
};
export default ParrentForm;
The expected data should look like this:
{
"user": {
"firstName": "Bill",
"lastName": "M.",
},
"things": {
"cars": [
{
"nr": 1,
"carsList": [
{
"name": "Car 1",
"nr": 1
},
{
"name": "Audi",
"nr": 2
},
,
{
"name": "Mercedes",
"nr": 3
}
]
},
{
"nr": 2,
"carsList": [
{
"name": "Bmw",
"nr": 1
}
]
}
]
}
}
How to modify the data inside onFinish function to get the result above?
demo: https://codesandbox.io/s/modest-cache-o0g65?file=/OuterForm.js:136-1755
First you have to destruct (doc) the form values object combining with spread operator (doc) to get the car-related values (I stored in variable carValues). After that, the only things left to do is manipulate with that variable, here I combined the use of Object.entries and Array.prototype.map
There a part with Number(key), because Object.entries() transforms object in to array of key-value pair, with key's type of string, so you have to cast it to Number first for 1-based index
const onFinish = values => {
const { firstName, lastName, nrOfCars, ...carValues } = values
const cars = Object.entries(carValues).map(([key, value]) => ({
nr: Number(key) + 1,
carsList: (value.cars || []).map((car, carIndex) => ({
nr: carIndex + 1,
name: car.name
}))
}))
const user = {
firstName,
lastName,
things: {
cars
}
}
console.log(JSON.stringify(user, null, 2))
}
Forked codesandbox for implementation

How to identify a certain object id of an array to change the state of an element in the same object?

I am trying to identify a specific panel in an array when it is expanded and be able to connect that panel's id to the button, as well as disable the button if no panel is expanded or more than 1 panel is expanded. For whatever reason, it's not taking in the id at all. Also, I am having problems with how to disable the button correctly.
export default class WorkoutList extends Component {
constructor(props) {
super(props);
this.state = {
workoutlist: [
{
id: uuid.v4(),
name: 'Leg Day',
date: '08/09/19',
duration: 60,
exerciselist: [
{
id: uuid.v4(),
exerciseName: 'Squats',
numberOfSets: 3,
reps: 12,
weight: 135,
},
{
id: uuid.v4(),
exerciseName: 'Leg press',
numberOfSets: 3,
reps: 10,
weight: 150,
},
{
id: uuid.v4(),
exerciseName: 'Lunges',
numberOfSets: 4,
reps: 12,
},
],
selected: false,
},
{
id: uuid.v4(),
name: 'Arm Day',
date: '08/10/19',
duration: 90,
exerciselist: [
{
id: uuid.v4(),
exerciseName: 'Bench Press',
numberOfSets: 5,
reps: 5,
weight: 225,
},
{
id: uuid.v4(),
exerciseName: 'Chest Flies',
numberOfSets: 3,
reps: 10,
weight: 50,
},
{
id: uuid.v4(),
exerciseName: 'Tricep Extensions',
numberOfSets: 4,
reps: 12,
weight: 70,
},
],
selected: false,
},
{
id: uuid.v4(),
name: 'Running',
date: '08/11/19',
duration: 40,
exerciselist: [],
selected: false,
},
],
disabled: false
}
this.handleSelectedPanel = this.handleSelectedPanel.bind(this);
this.handleButton = this.handleButton.bind(this);
}
handleSelectedPanel(id) {
const { workoutlist } = this.state;
this.setState({
workoutlist: workoutlist.map(workout => {
if (workout.id === id) {
workout.selected = !workout.selected
}
return workout;
})
})
}
handleButton(){
const { workoutlist, disabled } = this.state;
let count = 0;
workoutlist.map((workout) => {
if(workout.selected === true) {
count = count + 1;
}
return count;
})
if (count !== 1) {
this.setState({
disabled: true
})
} else {
this.setState({
disabled: false
})
}
return disabled;
}
render() {
const { workoutlist } = this.state;
return (
<div>
<CssBaseline />
<ClientMenuBar title="My Workouts" />
<div style={styles.workoutlist}>
<Paper style={styles.paper} elevation={0}>
{workoutlist.map((workout) => (
<WorkoutItem
key={workout.id}
workout={workout}
onSelectedPanel={this.handleSelectedPanel}
/>
))}
</Paper>
<Button
variant="contained"
color="primary"
size="small"
style={styles.button}
disabled={this.handleButton}
>
Start Workout
</Button>
</div>
</div>
)
}
}
export default class WorkoutItem extends Component {
constructor(props){
super(props);
this.handleSelectedPanel = this.handleSelectedPanel.bind(this);
}
handleSelectedPanel(e) {
this.props.onSelectedPanel(e.target.id);
}
render() {
const { id, name, date, duration, exerciselist } = this.props.workout;
return (
<ExpansionPanel style={styles.panel} id={id} onChange={this.handleSelectedPanel}>
<ExpansionPanelSummary>
<Typography variant="button" style={{ width: "33%" }}>
{name}
</Typography>
<Typography variant="button" style={{ width: "33%" }}>
({date})
</Typography>
<Typography align="right" style={{ width: "33%" }}>
~{duration} mins
</Typography>
</ExpansionPanelSummary>
<ExpansionPanelDetails>
<Table size="medium" style={styles.table}>
<TableHead>
<TableRow>
<TableCell padding="none">Name</TableCell>
<TableCell padding="none" align="right"># of sets</TableCell>
<TableCell padding="none" align="right">reps</TableCell>
<TableCell padding="none" align="right">weight</TableCell>
</TableRow>
</TableHead>
<TableBody>
{exerciselist.map((exercise) => (
<ExerciseList
key={exercise.id}
exercise={exercise}
/>
))}
</TableBody>
</Table>
<ExpansionPanelActions disableSpacing style={styles.actionButton}>
<Button color="primary" size="small" disableRipple>
edit
</Button>
</ExpansionPanelActions>
</ExpansionPanelDetails>
</ExpansionPanel>
)
}
}
It doesn't seem to be taking in the id at all, and when i try to disable the button, it throws this error:
Warning: Failed prop type: Invalid prop disabled of type function supplied to ForwardRef(Button), expected boolean.
The warning you are seeing comes from:
<Button
variant="contained"
color="primary"
size="small"
style={styles.button}
disabled={this.handleButton}
>
In the error it says a function is passed to disabled which should be a boolean, so change the prop that disabled takes to be that boolean (rather than the function this.handleButton).
e.target.id doesn't have what you actually want in there (it actually probably isn't a thing). You can use e.target.value to get a value out of something like an input where you want to get something information from the DOM node you are working with but in this case the information isn't something entered and actually something that the component already has in its scope (in the props). So instead of:
handleSelectedPanel(e) {
this.props.onSelectedPanel(e.target.id);
}
do this
handleSelectedPanel(e) {
this.props.onSelectedPanel(this.props.workout.id);
}

Categories