how to display json data in dropdown using reactj - javascript

i need to display data in dropdown i haven given json data with code.
this.setState({
data : [
{id:1,type:A},
{id:1,type:B},
{id:1,type:C},
]
})
<select className="form-control" onChange={(e) => this.handleChange(e)} >
<option >Select data</option>
{
this.state.data.map((i, h) =>
(<option key={h} value={i.type}>{i.type}</option>))
}
</select>

Json isn't correct...put quotation for string type value-"A", "B", "C"
data: [{ id: 1, type: "A" }, { id: 1, type: "B" }, { id: 1, type: "C" }]
JSX
class App extends Component {
state = {
data: [{ id: 1, type: "A" }, { id: 1, type: "B" }, { id: 1, type: "C" }]
};
handleChange = e => {
console.log(e.target.value);
};
render() {
return (
<div>
<select className="form-control" onChange={this.handleChange}>
<option>Select data</option>
{this.state.data.map((i, h) => (
<option key={h} value={i.type}>
{i.type}
</option>
))}
</select>
</div>
);
}
}

Related

How to update existing array in JavaScript?

I have function update tag, user can remove or add new tag.
this is the output of the temp
tag_temp = [{
db_id: 5,
id: 1,
name: 'Add Product'
},
{
db_id: 6,
id: 2,
name: 'New'
}, {
db_id: 7,
id: 3,
name: 'Test'
}
];
this is how I do it to achieve the above output.
if(e.tag.length > 0){
e.tag.map((e) => {
tag_temp.push({
"db_id" : e.db_id,
'id' : e.tag_id ,
'name' : e.tag_name,
});
});
console.log(tag_temp);
}
And now I want to perform update function, I have to compare the existing tag and push it into the finalized temp to fulfill my API Request.
I have this in my Postman API Request
"assign_tag":[
{
"db_id": 1,
"tag_id": 3,
"status": false
},
{
"db_id": null,
"tag_id": 3,
"status": true
}],
this is what I have tried on the update button
But I got error with
Uncaught ReferenceError: e is not defined at the line === e.db_id)[0].db_id;
finalized_temp = [];
tag_temp = tag_temp.filter(function (el){
if (el != null){
let db_id = tag_temp.filter((el) => el.id === e.db_id)[0].db_id;
let tag_id = tag_temp.filter((el) => el.id === e.tag_id)[0].tag_id;
let status = true;
finalized_temp.push({
"db_id" : db_id,
"tag_id" : tag_id,
"status" : status
})
}
});
I have to send data like this if I want to perform the update function how do I fix this problem ?
Example on how the concept is.
//tag_temp is current fetching of select option before updating into the new final_temp.
let tag_temp = [{
db_id: 5,
id: 1,
name: 'Add Product'
},
{
db_id: 6,
id: 2,
name: 'New'
}, {
db_id: 7,
id: 3,
name: 'Test'
}
];
$(document).ready(function() {
updateTag();
});
const updateTag = () => {
let finalized_temp =[]
let status = false;
//if db_id is null meaning status is set to true.
finalized_temp = [{
db_id: 5,
tag_id: 1,
status: 'false',
},
{
db_id: null,
tag_id: 4,
status: 'true',
}
];
console.log(finalized_temp);
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>
<label>Previous selected Tag :</label>
<select class="selectpicker" multiple data-live-search="true" id="mytitle">
<option value="1" selected>Add Product</option>
<option value="2" selected>New</option>
<option value="3" selected>Test </option>
<option value="4">Others</option>
</select>
<br><br><br>
<label>New Selected Tag :</label>
<select class="selectpicker" multiple data-live-search="true" id="mytitle">
<option value="1" selected>Add Product</option>
<option value="2">New</option>
<option value="3">Test</option>
<option value="4" selected>Others</option>
</select>
the logic for this is
// db_id null is because new data is inserted to the array so the status need to be changed into 'true' otherwise it will be set to 'false'
if(db_id == '' || db_id == null)
status = true
my expected output data will be like this
finalized_temp = [{
db_id: 5,
tag_id: 1,
status: 'false',
},
{
db_id: null,
tag_id: 3,
status: 'true',
}
];

Filling React JS dropdowns from Json data

I have some json data that looks like this:
{
"author1": {
"books": [{
"title": "title1"
},
{
"title": "title2"
}
],
"movies": [{
"title": "movie1"
},
{
"title": "movie2"
}
]
}
}
I want to have a dropdown that is populated with the authors (like author1). When that dropdown is selected, I then want to populate another dropdown with the keys for that author (books and movies).
So. if my json is in a variable named data, I want to populate the first dropdown with data.keys() and then the second with data[author].keys() where author is the value selected in the first dropdown.
I have seen a lot of examples of populating with json, but not with the keys. I am very new to React JS, so I am not sure how to do this.
Thanks
you can use the following flow.
const AuthorData = ({ symtomsData }) => {
const [data] = useState({
author1: {
books: [
{
title: "title1"
},
{
title: "title2"
}
],
movies: [
{
title: "movie1"
},
{
title: "movie2"
}
]
},
author2: {
books: [
{
title: "titleasd"
},
{
title: "titleqweqw"
}
],
movies: [
{
title: "movieqwewq"
},
{
title: "movieqweqwe"
}
]
}
});
const [authorWroks, setAuthorWorks] = useState({});
const [selectedData, setSelectedData] = useState([]);
const onChangeAuthor = useCallback(
(e) => {
const authorSelected = e.target.value;
if (authorSelected) {
setAuthorWorks(data[authorSelected]);
} else {
setAuthorWorks([]);
}
},
[data]
);
const changeItem = useCallback(
(e) => {
const itemSelected = e.target.value;
console.log("itemSelected", itemSelected);
if (itemSelected) {
console.log("authorWroks", authorWroks[itemSelected]);
setSelectedData(authorWroks[itemSelected]);
} else {
setSelectedData([]);
}
},
[authorWroks]
);
return (
<Grid>
<Col>
<select onChange={onChangeAuthor}>
<option value="">select</option>
{Object.keys(data).map((key, i) => (
<option value={key}>{key}</option>
))}
</select>
<br />
<div>
{Object.keys(authorWroks).length ? (
<select onChange={changeItem}>
<option value="">select</option>
{Object.keys(authorWroks || []).map((key, i) => (
<option onChange={changeItem} value={key}>
{key}
</option>
))}
</select>
) : undefined}
</div>
<div>
{selectedData.length ? (
<select>
<option value="">select</option>
{(selectedData || []).map((data, i) => (
<option onChange={changeItem} value={data.title}>
{data.title}
</option>
))}
</select>
) : undefined}
</div>
</Col>
</Grid>
);
};

Render dynamic elements ReactJS?

So i am trying to create a dynamic form with a couple of HTML inputs. i have an array of object Forms which contain the type of input that should be rendered. Currently i am able to render a couple of inputs like text area but how do i deal with radios, check boxes, selects along with their options? Any help will be appreciated.
See this CodeSandbox.
Check this Sample Code:-
class App extends React.Component {
state = {
Forms: [{
name: "select",
type: "select",
options: ["a", "b", "c"]
},
{
name: "Radio",
type: "radio",
options: ["a", "b", "c"]
},
{
name: "Date",
type: "date",
value: "2018-07-22"
},
{
name: "Text Input",
type: "text",
value: "text input"
},
{
name: "Checkbox",
type: "checkbox",
options: ["a", "b", "c"]
},
{
name: "Textarea",
type: "textarea",
value: "text area"
}
]
};
renderForm = () => {
return this.state.Forms.map((form, index) => ( <
label key = {index} > { form.name}
<input type = { form.type }
value = { form.value } />
<select/ >
</label>
));
};
render() {
return <div > {
this.renderForm()
} < /div>;
}
}
export default App;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Thank you for all the help. :)
Something like:
import React from "react";
import "./styles.css";
class App extends React.Component {
state = {
Forms: [
{ name: "select", type: "select", options: ["a", "b", "c"] },
{ name: "Radio", type: "radio", options: ["a", "b", "c"] },
{ name: "Date", type: "date", value: "2018-07-22" },
{ name: "Text Input", type: "text", value: "text input" },
{ name: "Checkbox", type: "checkbox", options: ["a", "b", "c"] },
{ name: "Textarea", type: "textarea", value: "text area" }
]
};
getField = (field) => {
switch(field.type) {
case 'date':
case 'text':
case 'textarea':
return <input type={field.type} value={field.value} />;
case 'select':
return <select name={field}>
{field.options.map(option =>
<option key={option} value={option}>{option}</option>
)};
</select>;
case 'radio':
case 'checkbox':
return <div>{field.options.map((option) =>
<label>
{option}:
<input key={option} type={field.type} name={option} value={option}/>
</label>
)}</div>;
default:
return <div>Unknown form field</div>;
}
}
renderForm = () => {
return this.state.Forms.map((field, index) => (
<label key={index}>
{field.name}
{this.getField(field)}
</label>
));
};
render() {
return <div>{this.renderForm()}</div>;
}
}
export default App;
You need to handle the different form types differently. See update example:
class App extends React.Component {
state = {
Forms: [{
name: "select",
type: "select",
options: ["a", "b", "c"]
},
{
name: "Radio",
type: "radio",
options: ["a", "b", "c"]
},
{
name: "Date",
type: "date",
value: "2018-07-22"
},
{
name: "Text Input",
type: "text",
value: "text input"
},
{
name: "Checkbox",
type: "checkbox",
options: ["a", "b", "c"]
},
{
name: "Textarea",
type: "textarea",
value: "text area"
}
]
};
renderForm = () => {
return this.state.Forms.map((form, index) => {
if (form.type === 'checkbox' || form.type === 'radio') {
return (
<span>
{form.name}
{form.options.map(opt => (
<label key={opt}>
<input type={form.type} group={form.name} value={opt} />
{opt}
</label>
))}
</span>
);
}
if (form.type === 'select') {
return (
<label key={index}>{form.name}
<select>
{form.options.map(opt => (
<option key={opt}>
{opt}
</option>
))}
</select>
</label>
);
}
return (
<label key={index}>{form.name}
<input type={form.type} value={form.value} />
</label>
);
});
};
render() {
return <div > {
this.renderForm()
} < /div>;
}
}
ReactDOM.render(<App />, document.querySelector("#app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>

Filling a model with a list from Textarea

Now I do not really understand you. Sorry, I just started this whole study not so long ago. I’ll try to explain again what I can’t do.
I have an empty object and an object with data with the same structure.
data: [
{id: 1, title: "title1"},
{id: 2, title: "title1"},
{id: 3, title: "title3"},
{id: 4, title: "title4"},
{id: 5, title: "title3"}
],
item: [
{
itemId: "",
itemname: ""
}
]
And I have select and textarear. Select have data, textarear empty. Textarear displays title.
I want to press a button. Selected item from select. copied to textarear (title only), and also itemId - this selected element id: 5 and itemname - the same title: "title3" element, was recorded in item [].
https://codesandbox.io/s/priceless-hermann-g9flw
Please do check now
import React from "react";
class App extends React.Component {
constructor() {
super();
this.state = {
id: null,
title: "",
filmItem: "",
listFilms: [],
data: [
{ id: 1, title: "title1" },
{ id: 2, title: "title2" },
{ id: 3, title: "title3" },
{ id: 4, title: "title4" }
],
item: []
};
this.onChange = this.onChange.bind(this);
this.onChangeArea = this.onChangeArea.bind(this);
this.addFilm = this.addFilm.bind(this);
this.choice = this.choice.bind(this);
}
addFilm(film) {
const selectedData = this.state.data.find(item => item.id == film);
console.log(selectedData);
this.setState({
listFilms: [...this.state.listFilms, selectedData.title],
item: [
...this.state.item,
{ itemId: selectedData.id, itemname: selectedData.title }
]
});
}
onChange = e => {
this.setState({ [e.target.name]: e.target.value });
};
onChangeArea = e => {
this.setState({ [e.target.name]: e.target.value.split("\n") });
};
choice(title) {
this.setState({ filmItem: title });
}
render() {
return (
<div className="App">
<div className="row App-main">
<div>
<select name="filmItem" size="4" onChange={e => this.onChange(e)}>
{this.state.data.map(film => (
<option key={film.title} value={film.id}>
{film.title}
</option>
))}
</select>
</div>
<div>
<button
className="editButton"
onClick={() => this.addFilm(this.state.filmItem)}
>
button
</button>
</div>
<div>
<textarea
name="films"
onChange={this.onChangeArea}
value={this.state.listFilms.map(r => r).join("\n")}
/>
</div>
<div>
<input type="text" name="text-input" onChange={this.onChange} />
</div>
</div>
<pre style={{ whiteSpace: "pre-wrap" }}>
{JSON.stringify(this.state)}
</pre>
</div>
);
}
}
export default App;

How to Filter array from state onChange based on category and revert to default?

For my class based component, I have a state object that contains a defined array named movies. I also have a handleMoviesFilter function, that is called onChange on the select tag.
How can I filter the options dynamically from my array, filter them onChange.. and revert when I pick another movie?
state = {
movies: [
{
name: 'Goodfellas',
category: 'crime'
},
{
name: 'Saving private ryan',
category: 'war'
},
{
name: 'The Shawshank Redemption',
category: 'drama'
}
]
}
handleMoviesFilter = e => {
let currentMovie = e.target.value;
const updateMoviesState = this.state.movies.filter(({ category }) =>
currentMovie.includes(category)
);
this.setState({
opleidingen: updateMoviesState,
isResetButtonActive: true,
});
}
<select id="lang" onChange={this.handleMoviesFilter}>
<option value="select">Select</option>
<option value="Goodfellas">Goodfellas</option>
<option value="Saving private ryan">Saving private ryan</option>
<option value="The Shawshank Redemption">The Shawshank Redemption</option>
</select>
If what you are trying to accomplish is based upon the selected option, filter the state.movies and return those in which match, then you would want to do something like the following...
state = {
movies: [
{
name: 'Goodfellas',
category: 'crime'
},
{
name: 'Saving private ryan',
category: 'war'
},
{
name: 'The Shawshank Redemption',
category: 'drama'
}
]
}
handleMoviesFilter = e => {
let currentMovie = e.target.value;
const updateMoviesState = this.state.movies.filter(movie => movie.name.toLowerCase() === currentMovie.toLowerCase());
this.setState({
movies: updateMoviesState,
isResetButtonActive: true,
});
}
<select id="lang" onChange={this.handleMoviesFilter}>
<option value="select">Select</option>
<option value="Goodfellas">Goodfellas</option>
<option value="Saving private ryan">Saving private ryan</option>
<option value="The Shawshank Redemption">The Shawshank Redemption</option>
</select>
You would want to
get the selected value
uppercase all of it's characters with toUpperCase()
filter state to get the movies that includes the selected value in it's name
filter & includes method used
state = {
movies: [
{
name: 'Goodfellas',
category: 'crime'
},
{
name: 'Saving private ryan',
category: 'war'
},
{
name: 'The Shawshank Redemption',
category: 'drama'
},
{
name: 'Good Riddance',
category: 'drama'
}
]
}
handleMoviesFilter = e => {
let currentMovie = e.target.value.toUpperCase();
//const updateMoviesState = this.state.movies.filter(movie => movie.name.toUpperCase() === currentMovie);
const updateMoviesState = this.state.movies.filter(movie => movie.name.toUpperCase().includes(currentMovie));
this.setState({
movies: updateMoviesState,
isResetButtonActive: true,
});
}
<select id="lang" onChange={this.handleMoviesFilter}>
<option value="select">Select</option>
<option value="Goodfellas">Goodfellas</option>
<option value="Saving private ryan">Saving private ryan</option>
<option value="The Shawshank Redemption">The Shawshank Redemption</option>
</select>
Test It Out
This snippet was made so you can test it out. This does NOT include react-js framework of course.
const state = {
movies: [
{
name: 'Goodfellas',
category: 'crime'
},
{
name: 'Saving private ryan',
category: 'war'
},
{
name: 'The Shawshank Redemption',
category: 'drama'
},
{
name: 'Good Riddance',
category: 'drama'
}
]
}
handleMoviesFilter = e => {
// get requested movie
let currentMovie = document.getElementById('textField').value.toUpperCase(); // t
console.log("Requested Movie:", currentMovie);
// array has a movie that equals selected movie
//const updateMoviesState = state.movies.filter(movie => movie.name.toUpperCase() === currentMovie);
// array has a movie whose name contain the phrase
const updateMoviesState = state.movies.filter(movie => movie.name.toUpperCase().includes(currentMovie));
console.log("Filter Result:", updateMoviesState);
}
<input id="textField"></input>
<button onclick="handleMoviesFilter(event)">Filter</button>

Categories

Resources