I'm designing a form in React that has a main form builder (Create Job.js) and some form pages (AdditionalInfo.js) and (Confirmation.js). this form had a tag input that allows you to choose tags from a drop-down list provided by an API. the selected items need to be shown later in the confirmation page.
This is my main form builder that has props and functions:(CreateJob.js)
state = {
step:1,
Title:'',
requirements:'',
Location:'',
Benefits:'',
Company:'',
InternalCode:'',
Details:'',
Tags:[],
Address:'',
Department:'',
Salary:''
}
handleDropDown = input => value => {
this.setState({ [input]: value });
}
render () {
const { step } = this.state
const {Title,Benefits,Company,InternalCode,Detailss,Tags,Address,Department,Salary,requirements,Location } = this.state;
const values ={Title,Benefits,Company,InternalCode,Detailss,Tags,Address,Department,Salary,requirements,Location}
return (
<div>
....
<AdditionalInfo
nextStep={this.nextStep}
prevStep={this.prevStep}
handleChange={this.handleChange}
handleChangeRaw={this.handleChangeRaw}
handleDropDown={this.handleDropDown}
values={values}
/>
<Confirmation
nextStep={this.nextStep}
prevStep={this.prevStep}
values={values}
/>
....
and this is my form page which includes the list from API and the drop down using react-select(AdditionalInfo.js):
export class AdditionalInfo extends Component {
state = {
locations:[],
departments: [],
tagsList:[],
}
componentDidMount() {
axios.get('/api/jobs/list-tags',{headers:headers}).then(respo =>{
console.log(respo.data)
this.setState({
tagsList:respo.data.map(Tags=>({label: Tags.name, value: Tags.id}))
})
console.log(this.state.tagsList)
})
}
render() {
const {values, handleDropDown} = this.props
<Select placeholder='Select from pre-created Tags 'onChange={handleDropDown('Tags')} defaultValue={values.Tags} required isMulti options={this.state.tagsList}/>
...
this is the list of tags received from the API:
Object { label: "MongoDB", value: 1 }
Object { label: "JavaScript", value: 2 }
Object { label: "HTML", value: 3 }
Object { label: "CSS", value: 4 }
...
And this is my Confirmation page which needs to show the info received from previous pages (Confirmation.js)
.....
render () {
const {
values: {
Title, Benefits,
Company, InternalCode, Detailss, Department,Tags, Salary,requirements,Location
}} = this.props
<Row> Tags: {Tags.join(", ")}</Row>
....
the problem is that, instead of showing tags on the page like putting the labels next to each other
:JavaScript,
MongoDB,
... it shows this
: [object Object], [object Object], [object Object], [object Object]. sorry for the long code but Im a beginner in JavaScript and I dont know how to handle it so it shows the labels. How can I achieve this?
You are doing great, and you have done right, just simple tweak you need.
If React show anything like [Object Object] it means you are trying to render Javascript Object not a single value because you have got Tags from props which is an Array of objects.
Use it like this, it will work like butter -
import React from 'react';
const Confirmation = () => {
const tags = [ // which you got from props
{ label: "MongoDB", value: 1 },
{ label: "JavaScript", value: 2 },
{ label: "HTML", value: 3 },
{ label: "CSS", value: 4 }
];
return (
<div>
{tags.map(tag => tag.label).join(', ')} {/* map over tags to get the array of tag labels */}
</div>
);
}
export default Confirmation;
Related
I am trying to use react-select in combination with match-sorter as described in this stackoverflow answer (their working version). I have an initial array of objects that get mapped to an array of objects with the value and label properties required by react-select, which is stored in state. That array is passed directly to react-select, and when you first click the search box everything looks good, all the options are there. The onInputChange prop is given a call to matchSorter, which in turn is given the array, the new input value, and the key the objects should be sorted on. In my project, and reproduced in the sandbox, as soon as you type anything into the input field, all the options disappear and are replaced by the no options message. If you click out of the box and back into it, the sorted options show up the way they should. See my sandbox for the issue, and here's the sandbox code:
import "./styles.css";
import { matchSorter } from "match-sorter";
import { useState } from "react";
import Select from "react-select";
const objs = [
{ name: "hello", id: 1 },
{ name: "world", id: 2 },
{ name: "stack", id: 3 },
{ name: "other", id: 4 },
{ name: "name", id: 5 }
];
const myMapper = (obj) => {
return {
value: obj.id,
label: <div>{obj.name}</div>,
name: obj.name
};
};
export default function App() {
const [options, setOptions] = useState(objs.map((obj) => myMapper(obj)));
return (
<Select
options={options}
onInputChange={(val) => {
setOptions(matchSorter(options, val, { keys: ["name", "value"] }));
}}
/>
);
}
I am sure that the array in state is not getting removed or anything, I've console logged each step of the way and the array is definitely getting properly sorted by match-sorter. It's just that as soon as you type anything, react-select stops rendering any options until you click out and back in again. Does it have something to do with using JSX as the label value? I'm doing that in my project in order to display an image along with the options.
I had to do two things to make your code work:
Replaced label: <div>{obj.name}</div> with label: obj.name in your mapper function.
I am not sure if react-select allows html nodes as labels. Their documentation just defines it as type OptionType = { [string]: any } which is way too generic for anything.
The list supplied to matchSorter for matching must be the full list (with all options). You were supplying the filtered list of previous match (from component's state).
const objs = [
{ name: "hello", id: 1 },
{ name: "world", id: 2 },
{ name: "stack", id: 3 },
{ name: "other", id: 4 },
{ name: "name", id: 5 }
];
const myMapper = (obj) => {
return {
value: obj.id,
label: obj.name, // -------------------- (1)
name: obj.name
};
};
const allOptions = objs.map((obj) => myMapper(obj));
export default function App() {
const [options, setOptions] = useState(allOptions);
return (
<Select
options={options}
onInputChange={(val) => {
setOptions(
matchSorter(
allOptions, // ----------------> (2)
val,
{ keys: ["name", "value"]
}
));
}}
/>
);
}
I am using React Select (https://react-select.com/home) which contains a bunch of options and the onChange handler will identify the selected items and push it into a State array.
The issue im running into is how to remove unselected items from the State array:
import Select from 'react-select'
const [selectedTeams, setSelectedTeams] = useState([]);
function manageSelectedTeams(event) {
console.log('function triggered')
setSelectedTeams([])
event.forEach((team) => {
console.log(team.value)
setSelectedTeams(() => [...selectedTeams, team.value])
})
}
data = [
{
label: "Example"
value: "example"
},
{
label: "Example"
value: "example"
},
{
label: "Example"
value: "example"
},
]
return (
<Select isMulti options={data} onChange={(e) => manageSelectedTeams(e)} closeMenuOnSelect={false} placeholder={"Teams will auto populate here once Location is defined above"} />
)
How would I tackle removing items from selectedTeams when a particular option is unselected/unticked
TIA
react-select handles the insert and delete for you so do not need to create a separate logic for it. When we use onChange the array of selected objects could be one possible parameter. You can refer to the same in the documentation. https://react-select.com/props
Thus you need to update your code as follows:
function manageSelectedTeams(data) {
let finalValueList = data.map((item) => item.value);
console.log(finalValueList);
setSelectedTeams(finalValueList);
}
return (
<Select
isMulti
options={data}
onChange={manageSelectedTeams} //UPDATED
closeMenuOnSelect={false}
placeholder={
"Teams will auto populate here once Location is defined above"
}
/>
);
For some reason my React component seems to remember its old state when going to another tab and back again, instead of reloading completely.
Basically when I click on the "Create" tab in my navbar and back to the "Board" tab data is populated twice instead of once, see image below. When going back the Board component this.state has two of each taskIds, as if it the component state still had the data from the initial page load when loading again. I have a React component looking like this:
const columnOrder = ['todo', 'in-progress', 'in-review', 'done']
const EMPTY_COLUMNS = {
'todo': {
id: 'todo',
title: 'TODO',
taskIds: []
},
'in-progress': {
id: 'in-progress',
title: 'In Progress',
taskIds: [],
},
'in-review': {
id: 'in-review',
title: 'In Review',
taskIds: []
},
'done': {
id: 'done',
title: 'Done',
taskIds: []
}
};
export class Board extends Component {
constructor(props) {
super(props);
this.onLoadEpic = this.onLoadEpic.bind(this);
this.state = {
columnOrder: columnOrder,
columns: {
'in-progress': {
id: 'in-progress',
title: 'In Progress',
taskIds: [],
},
// ...more columns similar to above
},
};
// Load state data on mount
componentDidMount() {
loadEpic(arg1, arg2);
}
// Async function loading items from DB and formatting into useful columns
async loadEpic(arg1, arg2) {
axios.get(...)
.then((response) => {
let data = response.data;
let newTasks = {};
let newColumns = EMPTY_COLUMNS;
data.taskItems.forEach(function(item) {
let id = item.id.toString();
newColumns[item.status]["taskIds"].push(id);
newTasks[id] = {
...item,
id: id
}
});
this.setState({
tasks: newTasks,
columns: newColumns
});
})
}
render() {
// Prints ["7"] on initial load and ["7", "7"] after going back and forth
console.log(this.state.columns["in-progress"].taskIds);
return (
// Simplified, but this is the main idea
<Container>
<DragDropContext onDragEnd={this.onDragEnd}>
{
this.state.columnOrder.map((columnId) => {
const column = this.state.columns[columnId]
const tasks = column.taskIds.map(taskId => this.state.tasks[taskId]
return (
<Column key={column.id} column={column} tasks={tasks}/>
)
}
}
</DragDropContext>
</Container>
)
}
}
and an App.js with Routing looking like this:
export default class App extends Component {
static displayName = App.name;
render () {
return (
<Layout>
<Route exact path='/' component={Board} />
<Route exact path='/create' component={Create} />
</Layout>
);
}
}
Okay, so I figured it out: it's the EMPTY_COLUMNS constant that is bugging out. When the component is re-rendered, the same EMPTY_COLUMNS object is referenced - so the constant is being appended to. Instead, I should make a copy of the empty columns:
// Before - same object is being appended to, doesn't work
let newColumns = EMPTY_COLUMNS;
// After - create a deep copy of the constant, does work
let newColumns = JSON.parse(JSON.stringify(EMPTY_COLUMNS));
I want to add multi language option in mui Datatables. I can change the translations but when I want to change language, I tried to give another object with the other translations (this object if I do console log I can see the changes) but the label texts not change.
I used a contextProvider to change the language selected and then get the specific dictionary with the translations.
Is a class component, so I did a static contextType with the correct provider.
Is there any possibility to re-render the element with another options or something like that?
options = {
textLabels: this.context.translation.dataTables.textLabels
};
return(
<MUIDataTable
title={this.context.language.value}
data={data}
columns={columns}
options={options}
/>
);
The best approach to re-render Mui-Datatables its updating the key of the table
key={this.context.language.value}
<MUIDataTable
key={this.context.language.value}
title={this.context.language.value}
data={data}
columns={columns}
options={options}
/>
You can force React component rendering:
There are multiple ways to force a React component rendering but they are essentially the same. The first is using this.forceUpdate(), which skips shouldComponentUpdate:
someMethod() {
// Force rendering without state change...
this.forceUpdate();
}
Assuming your component has a state, you could also call the following:
someMethod() {
// Force rendering with a simulated state change
this.setState({ state: this.state });
}
use customRowRender Function in the options and manipulate table with respect to language
Override default row rendering with custom function.
customRowRender(data, dataIndex, rowIndex) => React Component
In MUIDataTable, We can override label name by providing label in MUIDataTableColumnDef options while making column.
Example :
const columns: MUIDataTableColumnDef[] = [
{
name: 'Id',
label: 'ID',
options: {
download: false,
customBodyRenderLite: (index: number) => {
const desc: Description = evenMoreAbout[index]
return <BasicInfo obj={desc} setIconClicked={setIconClicked} />
}
}
},
{
name: 'id',
label: 'ID',
options: {
display: 'excluded',
download: true,
customBodyRender: desc => desc.id
}
}]
Even though if we still want to over ride the label name on some condition of data using customHeadLabelRender ... we can as like below example
const columns: MUIDataTableColumnDef[] = [
{
name: 'Id',
label: '',
options: {
download: false,
customBodyRenderLite: (index: number) => {
const desc: Description = evenMoreAbout[index]
return <BasicInfo obj={desc} setIconClicked={setIconClicked} />
},
customHeadLabelRender: (dataIndex: number, rowIndex: number) => {
return 'ID';
}
}
}
]
I am working on a redux project where I want to retrieve the values stored in API server.I want to store the data from the API in my redux store and then retrieve the values and display it in my react component.The data in the API server is in the form of an object but has a unique id for each value.So,in my case, the data is a list of posts.So, each post has a unique id and has all the other details like timestamp,post-title,post-author etc.This is how the default data from the API for posts looks like:
const defaultData = {
"8xf0y6ziyjabvozdd253nd": {
id: '8xf0y6ziyjabvozdd253nd',
timestamp: 1467166872634,
title: 'Udacity is the best place to learn React',
body: 'Everyone says so after all.',
author: 'thingtwo',
category: 'react',
voteScore: 6,
deleted: false,
commentCount: 2
},
"6ni6ok3ym7mf1p33lnez": {
id: '6ni6ok3ym7mf1p33lnez',
timestamp: 1468479767190,
title: 'Learn Redux in 10 minutes!',
body: 'Just kidding. It takes more than 10 minutes to learn technology.',
author: 'thingone',
category: 'redux',
voteScore: -5,
deleted: false,
commentCount: 0
}
}
Note: The "id" which is a random number here(like "8xf0y6ziyjabvozdd253nd") becomes an integer, i.e the 1st post gets the id 1 ,the 2nd gets 2.
So, I am able to store the data from posts API in my redux "Store". And I converted the posts object into an array(as we cannot map over an object) because I want to map over this array and show the data in my React component.But,I am not able to see the result of the array in my component,maybe that's because it has an id before each object in the array.This is how I am trying to map over the arrayand I do not get any error,but I do not see the results from the object in component.My component file looks like this:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchPosts } from '../actions';
import _ from 'lodash';
class PostsIndex extends Component {
componentDidMount() {
this.props.dispatch(fetchPosts())
.then(() => {
this.setState({
loading : false
});
// console.log(this.props.posts.posts[0])
})
}
render() {
// console.log(this.props.posts.posts)
const obj = this.props.posts.posts;
let arr;
if (obj) {
arr = Object.values(obj); //Converting an Object into an array
}
console.log(arr); //returns the converted array from an object
return(
<div>
{
arr ?
<div>
{ arr.map(post =>
{
<div>
{post.title}
</div>
})
}
</div>
:
<div>
No Data
</div>
}
</div>
);
}
}
function mapStateToProps(state) {
return { posts: state.posts };
}
export default connect(mapStateToProps)(PostsIndex);
And when I console.log my state,the converted array looks like this:
When expanded looks like:
I want to retrieve almost all of the values from the above array.Can anyone please show me how to get the data from the array and map over the array to show the values in my React component?
You can keep your data as an object, and use Object.keys to get an array of keys, map over the keys, and use the keys to access nested objects. If you don't know the shape of your data source, you could use recursion.
Here is a working code sandbox example where I've taken your data source and turned it into a table to illustrate how to do so.
Here is the code:
import React from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
const defaultData = {
"8xf0y6ziyjabvozdd253nd": {
id: '8xf0y6ziyjabvozdd253nd',
timestamp: 1467166872634,
title: 'Udacity is the best place to learn React',
body: 'Everyone says so after all.',
author: 'thingtwo',
category: 'react',
voteScore: 6,
deleted: false,
commentCount: 2
},
"6ni6ok3ym7mf1p33lnez": {
id: '6ni6ok3ym7mf1p33lnez',
timestamp: 1468479767190,
title: 'Learn Redux in 10 minutes!',
body: 'Just kidding. It takes more than 10 minutes to learn technology.',
author: 'thingone',
category: 'redux',
voteScore: -5,
deleted: false,
commentCount: 0
}
}
const TableHeader = ({ fields }) => (
<thead>
<tr>
{
fields.map( field => <th key={ field }>{ field }</th>)
}
</tr>
</thead>
);
const TableBody = ({ data }) => (
<tbody>
{
Object.keys(data).map(
datum =>
<tr>
{
Object.keys(data[datum]).map(
field => <td>{data[datum][field]}</td>
)
}
</tr>
)
}
</tbody>
);
const App = () => (
<table>
<TableHeader fields={ Object.keys(defaultData[Object.keys(defaultData)[0]]) } />
<TableBody data={defaultData} />
</table>
);
render(<App />, document.getElementById('root'));
You need map your data. Something like this:
<div>
<ul>
{props.incomingDataArray.map((singleArrayItem, index) => {
return (
<li key="list + index">{singleArrayItem.commentCount}</li>
<li key="list + index">{singleArrayItem.timestamp}</li>
)
})
}
</ul>
<div>
you forgot return inside your map.
render() {
const obj = this.props.posts.posts;
let arr;
if (obj) {
arr = Object.values(obj); //Converting an Object into an array
}
return (
<div>
{ arr ?
<div>
{ arr.map(post => {
return (
<div key={post.id}>
{post.title}
</div>
)
})
}
</div> :
<div>
No Data
</div>
}
</div>
);
}
or, alternatively, drop the curly braces with a oneliner:
arr.map(post => (<div key={post.id}>
{post.title}
</div>
)
)
and don't forget the key attribute.
I also suggest you abstract way your dumb components. It'll make your code more readable.