I am a student who is practicing react js, for this I am developing a calendar in which you can put notes, as you will see there are some notes that I have put by hand. I have installed axios to work the json and the get of the data does it well, but when I try to set a new data it gives me this error.
the browser console shows me this error
PATCH http://localhost:5000/January/3/alarms/ 404 (Not Found) Uncaught
(in promise) Error: Request failed with status code 404 at
createError (createError.js:16) at settle (settle.js:17) at
XMLHttpRequest.handleLoad (xhr.js:62)
this is my JSOn
{
"January": [
{
"id": 1,
"alarms": [
{
"name": "Medico",
"initHour": "12:00",
"endHour": "12:35"
},
{
"name": "fisio",
"initHour": "16:00",
"endHour": "17:00"
},
{
"name": "desayuno con Rick",
"initHour": "8:00",
"endHour": "9:00"
}
]
},
{
"id": 2,
"alarms": [
{
"name": "Desayuno",
"initHour": "9:00",
"endHour": "9:35"
},
{
"name": "banco",
"initHour": "11:00",
"endHour": "12:00"
}
]
},
{
"id": 3,
"alarms": []
},{
"id": 4,
"alarms": []
},
{
"id": 5,
"alarms": []
},
{
"id": 6,
"alarms": []
},
{
"id": 7,
"alarms": []
},
{
"id": 8,
"alarms": []
},
{
"id": 9,
"alarms": [
{
"name": "fisio",
"initHour": "16:00",
"endHour": "17:00"
}
]
},
{
"id": 10,
"alarms": []
},
{
"id": 11,
"alarms": []
},
{
"id": 12,
"alarms": []
},
{
"id": 13,
"alarms": []
},
{
"id": 14,
"alarms": []
},
{
"id": 15,
"alarms": []
},
{
"id": 16,
"alarms": [
{
"name": "fisio",
"initHour": "16:00",
"endHour": "17:00"
}
]
},
{
"id": 17,
"alarms": []
},
{
"id": 18,
"alarms": []
},
{
"id": 19,
"alarms": []
},
{
"id": 20,
"alarms": []
},
{
"id": 21,
"alarms": []
},
{
"id": 22,
"alarms": []
},
{
"id": 23,
"alarms": [
{
"name": "fisio",
"initHour": "16:00",
"endHour": "17:00"
}
]
},
{
"id": 24,
"alarms": []
},
{
"id": 25,
"alarms": []
},
{
"id": 26,
"alarms": []
},
{
"id": 27,
"alarms": []
},
{
"id": 28,
"alarms": []
},
{
"id": 29,
"alarms": []
},
{
"id": 30,
"alarms": [
{
"name": "fisio",
"initHour": "16:00",
"endHour": "17:00"
}
]
},
{
"id": 31,
"alarms": []
}
]
}
and this is my code
import React, {useEffect, useState} from "react";
import './Calendar.scss';
import axios from "axios";
import Day from "./Day/Day";
import Modal from 'react-modal';
import { useForm } from 'react-hook-form';
const customStyles = {
content : {
top : '50%',
left : '50%',
right : 'auto',
bottom : 'auto',
marginRight : '-50%',
transform : 'translate(-50%, -50%)'
}
};
export default function Calendar() {
let subtitle;
const { register, handleSubmit} = useForm();
const [days, setDays] = useState([]);
const [modalIsOpen,setIsOpen] = useState(false);
const [id, setId] = useState([]);
Modal.setAppElement('#root')
useEffect(() => {
axios.get('http://localhost:5000/January').then(res => {
setDays(res.data);
});
}, [])
const onSubmit = form => {
console.log('http://localhost:5000/January/' + id + '/alarms', form);
axios.patch('http://localhost:5000/January/' + id + '/alarms/', form).then(res => {
console.log(res);
});
}
function openModal(id) {
setIsOpen(true);
setId(id);
}
function afterOpenModal() {
// references are now sync'd and can be accessed.
subtitle.style.color = 'rgb(72, 181, 163)';
}
function closeModal(){
setIsOpen(false);
}
return (
<div className="b-calendar">
<h3 className="b-calendar__title">January</h3>
<div className="b-calendar__headers">
<div>Monday</div>
<div>Tuesday</div>
<div>Wednesday</div>
<div>Thursday</div>
<div>Friday</div>
<div>Saturday</div>
<div>Sunday</div>
</div>
<div className="b-calendar__content">
<div className="b-december"><h1>28</h1></div>
<div className="b-december"><h1>29</h1></div>
<div className="b-december"><h1>30</h1></div>
<div className="b-december"><h1>31</h1></div>
{days.map((item, index) =>
<div key={index+1} id={index+1} onClick={() => openModal(item.id)}>
<Day items={item}/>
</div>
)}
</div>
<Modal
isOpen={modalIsOpen}
onAfterOpen={afterOpenModal}
onRequestClose={closeModal}
style={customStyles}
contentLabel="Example Modal"
>
<h2 ref={_subtitle => (subtitle = _subtitle)}>Añadir Cita</h2>
<form className="b-loginForm" onSubmit={handleSubmit(onSubmit)}>
<label htmlFor="initHour">
<span className="b-text-label">Init hour</span>
<input id="initHour" className="b-input" type="time" name="initHour" ref={register({ required: true})} />
</label>
<label htmlFor="endHour">
<span className="b-text-label">End hour</span>
<input id="endHour" className="b-input" type="time" name="endHour" ref={register()} />
</label>
<label htmlFor="name">
<span className="b-text-label">Alarms name</span>
<input id="name" className="b-input" type="text" name="name" ref={register({ required: true})} />
</label>
<input className="b-btn" type="submit" value="Guardar" />
<button onClick={closeModal}>Salir</button>
</form>
</Modal>
</div>
)
}```
[1]: https://i.stack.imgur.com/PDVPD.png
Related
i have a GET api that gets these data:
{
"questions": [
{
"question": {
"id": 110,
"title_text": "question title 1",
"metric_id": 27,
"sub_metric_id": 28,
"image_url": null
},
"answers": [
{
"id": 104,
"title_text": "answer 1",
"image_url": null,
"question_id": 110
},
{
"id": 105,
"title_text": "answer 2",
"image_url": null,
"question_id": 110
},
{
"id": 106,
"title_text": "answer 3",
"image_url": null,
"question_id": 110
}
]
},
{
"question": {
"id": 111,
"title_text": "question title 2",
"metric_id": 31,
"sub_metric_id": 32,
"image_url": null
},
"answers": [
{
"id": 108,
"title_text": "this answer my answer",
"image_url": null,
"question_id": 111
},
{
"id": 109,
"title_text": "my answerio",
"image_url": null,
"question_id": 111
},
{
"id": 110,
"title_text": "hello every body",
"image_url": null,
"question_id": 111
}
]
},
{
"question": {
"id": 112,
"title_text": "question 3 question",
"metric_id": 27,
"sub_metric_id": 29,
"image_url": null
},
"answers": [
{
"id": 111,
"title_text": "answer111",
"image_url": null,
"question_id": 112
},
{
"id": 112,
"title_text": "answer222",
"image_url": null,
"question_id": 112
},
{
"id": 114,
"title_text": "answer3333",
"image_url": null,
"question_id": 112
}
]
}
]
}
I get this data through the following code and show it:
const [testQuestions, setTestQuestions] = useState([]);
useEffect(() => {
const fetchTestsQuestion = async () => {
try {
const { data } = await axios.get(
"url"
);
setTestQuestions(data.questions);
} catch (error) {
console.error(error.message);
}
};
fetchTestsQuestion();
}, []);
<form className="App">
{testQuestions.map((item) => {
return (
<>
<h1 value={item.question.id}>{item.question.title_text}</h1>
{item.answers.map((sub, index) => {
return (
<>
<input
type="radio"
id={index}
name={sub.question_id}
value={sub.title_text}
/>
<label for={sub.title_text}>{sub.title_text} </label>
<br />
</>
);
})}
</>
);
})}
<button className="btn btn-default" type="submit">
Submit
</button>
</form>
And I have another POST api that should send data when the button is clicked, but I don't know how to create useState or object to save data for send this data. Because I have to send the data as follows
{
"result": [
{
"questionId" : 110 ,
"answerId" : 105 ,
"metricId" : 27,
"subMetricId" : 28
} ,
{
"questionId" : 111 ,
"answerId" : 109 ,
"metricId" : 31,
"subMetricId" : 32
} ,
{
"questionId" : 112 ,
"answerId" : 113 ,
"metricId" : 27,
"subMetricId" : 29
} ,
{
"questionId" : 113 ,
"answerId" : 118,
"metricId" : 27,
"subMetricId" : 28
}
]
}
for more information:
questionId is : "question": {"id": 110,
"answerId" is : "id": 104,
"metricId" : 27, and "subMetricId" : 28 are in questions.question
you should use onChange in input element
<input
type="radio"
id={index}
name={sub.question_id}
value={sub.id}
onChange={(e) => {
setData(e.target.value);
}}
/>
and use foreach loop for get data
let store = [];
const setData= (answerId) => {
testQuestions.forEach(function (obj) {
obj.answers.map(function (o) {
if (answerId == o.id) {
store.forEach(function (data, index) {
if (obj.question.id == data.questionId) {
store.splice(index, 1);
}
});
store.push({
questionId: obj.question.id,
answerId: answerId,
metricId: obj.question.metric_id,
subMetricId: obj.question.sub_metric_id,
});
}
});
});
I have the following code which displays record from Monday API successfully.
I can get the JSON record via {JSON.stringify(this.state.datax, null, 2)} as per below
[ { "items": [ { "id": "3150569213", "name": "Task 1", "column_values": [ { "id": "fullname", "value": null }, { "id": "status", "value": null }, { "id": "email", "value": null }, { "id": "phone_number", "value": null }, { "id": "address", "value": null }, { "id": "product", "value": null }, { "id": "quantity", "value": null }, { "id": "reward", "value": null } ] }, { "id": "3150569636", "name": "Recycle Products Share By ann balling", "column_values": [ { "id": "fullname", "value": "\"ann balling\"" }, { "id": "status", "value": "{\"index\":0}" }, { "id": "email", "value": "{\"text\":\"ann1#gmail.com\",\"email\":\"ann1#gmail.com\",\"changed_at\":\"2022-08-27T12:16:47.728Z\"}" }, { "id": "phone_number", "value": "{\"phone\":\"1234567890\",\"countryShortName\":null}" }, { "id": "address", "value": "{\"lat\":\"Texas,\",\"lng\":\"US\",\"address\":\"unknown\"}" }, { "id": "product", "value": "{\"text\":\"Paper,Bottles,Plastic Cans\"}" }, { "id": "quantity", "value": "\"200\"" }, { "id": "reward", "value": "\"Gift\"" } ] } ] } ]
How do I get values for name, fullname, email?
Here is the code:
import React from 'react';
import './App.css';
import mondaySdk from 'monday-sdk-js';
import 'monday-ui-react-core/dist/main.css';
const monday = mondaySdk();
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: false,
datax: [],
};
}
componentDidMount() {
monday
.api(
`query {boards (ids: 3150569212) {items(limit: 3 page: 1) {id name column_values {
id
value
} }}}`
)
.then((res) => {
console.log(res);
this.setState({ datax: res.data.boards });
//this.setState({datax: res.data.boards[0].items});
});
}
render() {
const { loading } = this.state;
return (
<div>
<table class="table table-hover">
<thead>
<tr>
<th>Name</th>
<th>Fullname</th>
<th>Email</th>
</tr>
</thead>
<tbody>
{this.state.datax.map((i, index) => (
<tr key={index}>
<td>{i.name}</td>
<td>{i.fullname}</td>
<td>{i.email}</td>
</tr>
))}
</tbody>
</table>
{JSON.stringify(this.state.datax, null, 2)}
<br />
</div>
);
}
}
export default App;
You need to map the first element in that case items and then map column_values since it is an array:
{this.state.datax[0].items.map((i, index) => (
<tr key={index}>
<td>{i.name}</td>
<td>{i.fullname}</td>
<td>{i.column_values.map((val) => val.value)}</td>
</tr>
))}
I have try it with the example you send and the output I get is like this, not very clean:
The code below is working fine and it display record from Monday API.
Here is the outputed JSON record via JSON.stringify()
[ { "id": "3150569213", "name": "Task 1", "column_values": [ { "id": "fullname", "value": null }, { "id": "status", "value": null }, { "id": "email", "value": null }, { "id": "phone_number", "value": null }, { "id": "address", "value": null }, { "id": "product", "value": null }, { "id": "quantity", "value": null }, { "id": "reward", "value": null } ] }, { "id": "3150569636", "name": "Recycle Products Share By ann balling", "column_values": [ { "id": "fullname", "value": "\"ann balling\"" }, { "id": "status", "value": "{\"index\":0}" }, { "id": "email", "value": "{\"text\":\"nancy#gmail.com\",\"email\":\"nancy#gmail.com\",\"changed_at\":\"2022-08-27T12:16:47.728Z\"}" }, { "id": "phone_number", "value": "{\"phone\":\"1234567890\",\"countryShortName\":null}" }, { "id": "address", "value": "{\"lat\":\"Texas,\",\"lng\":\"US\",\"address\":\"unknown\"}" }, { "id": "product", "value": "{\"text\":\"Paper,Bottles,Plastic Cans\"}" }, { "id": "quantity", "value": "\"200\"" }, { "id": "reward", "value": "\"Gift\"" } ] } ]
The property i.column_values[0].value displays record "Nancy More" and I remove the double quotes around it using json.parse() hence JSON.parse(i.column_values[0].value) and its okay.
Here is my issue. The property i.column_values[1].value display record object
{"text":"nancy#gmail.com","email":"nancy#gmail.com","changed_at":"2022-08-27T12:16:47.728Z"}
How do I get email value hence nancy#gmail.com.
Here is the code
import React from "react";
import "./App.css";
import mondaySdk from "monday-sdk-js";
const monday = mondaySdk();
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: false,
datax: [],
};
}
componentDidMount() {
monday.api(`query {boards (ids: 34443234) {items(limit: 3 page: 1) {id name column_values {
id
value
} }}}`).then(res => {
console.log(res);
this.setState({datax: res.data.boards[0].items});
});
}
render() {
const {loading } = this.state;
return (
<div>
<table class="table table-hover">
<thead>
<tr>
<th>Fullname</th>
<th>Email</th>
</tr>
</thead>
<tbody>
{this.state.datax.map((i, index) => (
<tr key={index}>
<td>{JSON.parse(i.column_values[0].value)}</td>
<td>{i.column_values[1].value}</td>
</tr>
))}
</tbody>
</table>
{JSON.stringify(this.state.datax, null, 2)}
<br />
</div>
);
}
}
export default App;
The code below is how I got the email address value working
<td>{i.column_values[2].value.split(':')[1].split('"')[1]}</td>
I am trying to make a simple Quiz work with Redux following this example in https://www.codeproject.com/Articles/5130417/Quiz-Application-in-React-Using-Redux . Somehow I think the quizLoad Reducer is not getting the data or isn't even being called correctly.
This is my Reducer:
const QUIZ_LOAD = 'QUIZ_LOAD';
const QUIZ_ANSWER = 'QUIZ_ANSWER';
const QUIZ_SUBMIT = 'QUIZ_SUBMIT';
const PAGER_UPDATE = 'PAGER_UPDATE';
const INITIAL_STATE = {
quiz: {
config: {
'allowBack': false,
'allowReview': false,
'autoMove': true, // if true, it will move to next question automatically when answered.
'duration': 0, // indicates the time in which quiz needs to be completed. 0 means unlimited.
'pageSize': 1,
'requiredAll': false, // indicates if you must answer all the questions before submitting.
'richText': false,
'shuffleQuestions': false,
'shuffleOptions': false,
'showClock': false,
'showPager': true,
'theme': 'none'
},
questions: []
},
mode: 'quiz',
pager: {
index: 0,
size: 1,
count: 1
}
}
export default (state = INITIAL_STATE, action) => {
const { type, payload } = action;
console.log('REDUCERRRRRRRRR')
switch (type) {
case PAGER_UPDATE:
return { ...state, pager: payload, mode: 'quiz' };
case QUIZ_LOAD:
return { ...state, quiz: payload };
case QUIZ_SUBMIT:
return { ...state, mode: payload };
case QUIZ_ANSWER:
return { ...state, quiz: payload };
default:
return state;
}
};
// <<<ACTIONS>>>
export const pagerUpdate = (payload) => {
return {
type: PAGER_UPDATE,
pager: payload,
mode: 'quiz'
};
};
export const quizLoad = (payload) => {
return {
type: QUIZ_LOAD,
quiz: payload
};
};
export const quizSubmit = (payload) => {
return {
type: QUIZ_SUBMIT,
mode: { payload }
};
};
export const quizAnswer = (payload) => {
return {
type: QUIZ_ANSWER,
quiz: { payload }
}
};
This is my component and where I get the error
"Unhandled Rejection (TypeError): Cannot read property 'config' of
undefined eval
C:\Users\Willkommen\Documents\MyPension\REPOs\web-best\src\pages\header\vertragsCheck\index.js:69:6"
import React from "react";
import { connect } from "react-redux";
import Quiz from "./quiz/Quiz";
import {
pagerUpdate,
quizLoad
} from "redux/vertragsCheck/vertragscheckReducer";
import SEOTitle from "components/SEO/seoTitle";
import WavySectionWrapper from "components/Layouts/Containers/wavySectionWrapper/wavySectionWrapper";
import WavyPageTitleWrapper from "components/Sections/WavyPageTitle/WavyPageTitle";
import Button from "components/Button/Button";
import "./vertragsCheckSteps.scss";
const bgMobileImage =
"/images/illustrations/pages/Home/mobile/mobile-phone1.png";
class vertragsCheck extends React.Component {
state = {
// quizes: [
// { id: 'data/myPensionQuiz.json', name: 'VertragsCheck' },
// { id: 'data/myPensionTest.json', name: 'Rente' }
// ],
quizVisible: false,
quizId: "quizApi/quiz.json"
};
pager = {
index: 0,
size: 1,
count: 1
};
componentDidMount() {
this.load(this.state.quizId);
}
load(quizId) {
let url = quizId || this.props.quizId;
fetch(`../${url}`)
.then(res => res.json())
.then(res => {
let quiz = res;
quiz.questions.forEach(q => {
q.options.forEach(o => (o.selected = false));
});
debugger;
console.log("quizCONFIG", this.props.quiz);
quiz.config = Object.assign(this.props.quiz.config || {}, quiz.config);
this.pager.count = quiz.questions.length / this.pager.size;
this.props.onQuizLoad(quiz);
this.props.onPagerUpdate(this.pager);
});
}
// onChange = (e) => {
// this.setState({ quizId: e.target.value });
// this.load(e.target.value);
// }
handleClick = () => {
const { quizVisible } = this.state;
this.setState({ quizVisible: !quizVisible });
};
render() {
const quizVisible = this.state.quizVisible;
if (!quizVisible) {
return (
<WavySectionWrapper vertical>
<SEOTitle page="vertrags-check" />
<WavyPageTitleWrapper>
<div className="flex-container">
<div>
<h1>
Kostenloser <br />
Vertrags-Check
</h1>
<p>
Ist meine bestehender Vertrag zu teuer? <br />
Wie schneidet meine bestehen Altervorsorge ab? <br />
Wir helfen Dir Deine Altervorsorge zu optimieren.
</p>
<Button size="sm" onClick={this.handleClick}>
Jetzt prüfen
</Button>
</div>
<div>
<img src={bgMobileImage} alt="myPension mobile graphic" />
{/* <img
src="/images/background-elements/bg-vertical-section.svg"
/> */}
</div>
</div>
</WavyPageTitleWrapper>
</WavySectionWrapper>
);
} else if (quizVisible) {
return (
<Quiz
quiz={this.state.quiz}
quizId={this.state.quizId}
mode={this.state.mode}
/>
);
}
}
}
const mapStateToProps = state => {
return { ...state.quiz };
};
const mapDispatchToProps = dispatch => ({
onQuizLoad: payload => dispatch({ type: quizLoad, payload }),
onPagerUpdate: payload => dispatch({ type: pagerUpdate, payload })
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(vertragsCheck);
And this is my quiz data in public folder:
{
"id": 1,
"name": "Vertrags-check Quiz",
"description": "Vertrags-check Quiz determines if your actual pension contract is improvable",
"config": {
"showPager": false,
"allowBack": true,
"autoMove": true
},
"questions": [
{
"id": 1010,
"name": "Sind die Effektivkosten höher als 1,5%?",
"questionTypeId": 1,
"options": [
{
"id": 1055,
"questionId": 1010,
"name": "Ja",
"isAnswer": false
},
{
"id": 1056,
"questionId": 1010,
"name": "Nein",
"isAnswer": false
},
{
"id": 1057,
"questionId": 1010,
"name": "Weiß nicht",
"isAnswer": true
}
],
"questionType": {
"id": 1,
"name": "test type",
"isActive": true
}
},
{
"id": 1011,
"name": "Liegt Dein Rentenfaktor unter 27€?",
"questionTypeId": 1,
"options": [
{
"id": 1055,
"questionId": 1010,
"name": "Ja",
"isAnswer": false
},
{
"id": 1056,
"questionId": 1010,
"name": "Nein",
"isAnswer": false
},
{
"id": 1057,
"questionId": 1010,
"name": "Weiß nicht",
"isAnswer": true
}
],
"questionType": {
"id": 1,
"name": "test type",
"isActive": true
}
},
{
"id": 1012,
"name": "Erfolgt die Anlage zu weniger als 80% in Aktien?",
"questionTypeId": 1,
"options": [
{
"id": 1055,
"questionId": 1010,
"name": "Ja",
"isAnswer": false
},
{
"id": 1056,
"questionId": 1010,
"name": "Nein",
"isAnswer": false
},
{
"id": 1057,
"questionId": 1010,
"name": "Weiß nicht",
"isAnswer": true
}
],
"questionType": {
"id": 1,
"name": "test type",
"isActive": true
}
},
{
"id": 1013,
"name": "Ist Deine Rendite geringer als 3% p.A.?",
"questionTypeId": 1,
"options": [
{
"id": 1055,
"questionId": 1010,
"name": "Ja",
"isAnswer": false
},
{
"id": 1056,
"questionId": 1010,
"name": "Nein",
"isAnswer": false
},
{
"id": 1057,
"questionId": 1010,
"name": "Weiß nicht",
"isAnswer": true
}
],
"questionType": {
"id": 1,
"name": "test type",
"isActive": true
}
},
{
"id": 1014,
"name": "Zahlst Du für Flexibilität?",
"questionTypeId": 1,
"options": [
{
"id": 1055,
"questionId": 1010,
"name": "Ja",
"isAnswer": false
},
{
"id": 1056,
"questionId": 1010,
"name": "Nein",
"isAnswer": false
},
{
"id": 1057,
"questionId": 1010,
"name": "Weiß nicht",
"isAnswer": true
}
],
"questionType": {
"id": 1,
"name": "test type",
"isActive": true
}
},
{
"id": 1015,
"name": "Es gibt keine Steuervorteile bei deinem bestehendem Vertrag?",
"questionTypeId": 1,
"options": [
{
"id": 1055,
"questionId": 1010,
"name": "Ja",
"isAnswer": false
},
{
"id": 1056,
"questionId": 1010,
"name": "Nein",
"isAnswer": false
},
{
"id": 1057,
"questionId": 1010,
"name": "Weiß nicht",
"isAnswer": true
}
],
"questionType": {
"id": 1,
"name": "test type",
"isActive": true
}
},
{
"id": 1016,
"name": "Hast Du Deinen Vertrag nach 2005 abgeschlossen?",
"questionTypeId": 1,
"options": [
{
"id": 1055,
"questionId": 1010,
"name": "Ja",
"isAnswer": false
},
{
"id": 1056,
"questionId": 1010,
"name": "Nein",
"isAnswer": false
},
{
"id": 1057,
"questionId": 1010,
"name": "Weiß nicht",
"isAnswer": true
}
],
"questionType": {
"id": 1,
"name": "test type",
"isActive": true
}
}
]
}
There is problem probably here:
const mapStateToProps = state => { return { ...state.quiz } };
You are using object spread operator, which puts/maps content of the state.quiz into your props. Therefore there isn't any quiz in this.props.
Try to map the state.quiz to this.props.quiz this way:
const mapStateToProps = state => { return { quiz: state.quiz } };
You are also mapping actions to props incorrectly, try this:
const mapDispatchToProps = dispatch => ({
onQuizLoad: payload => dispatch(quizLoad(payload)),
onPagerUpdate: payload => dispatch(pagerUpdate(payload))
});
I am trying to display list dynamically when user click on input box. for that I took onChange event handle on input box and setting state to new data when user click on input box. but it is not giving me desired result. can anyone help me to solve the issue ? When user click on input box then only list should be displayed but in my case it's displaying already.
SearchBox.js
import React, { Component } from "react";
import SourceData from "../assets/continents.json";
class SearchBox extends Component {
state = {
value: ""
};
handleChange = e => {
this.setState({
sourceData: SourceData
});
};
render() {
const searhBox = (
<input type="text" value={this.state.value} onClick={this.handleChange} />
);
const selectBox2 = SourceData.map(option => <li>{option.continent}</li>);
return (
<React.Fragment>
<h2>Step 1</h2>
<h3>Select a continent.</h3>
{searhBox}
<ul>{selectBox2}</ul>
</React.Fragment>
);
}
}
export default SearchBox
continents.json
[
{
"continent": "Africa",
"countries": [
{
"name": "Nigeria",
"flag": "ð³ð¬"
},
{
"name": "Ethiopia",
"flag": "ðªð¹"
},
{
"name": "Egypt",
"flag": "ðªð¬"
},
{
"name": "DR Congo",
"flag": "ð¨ð©"
},
{
"name": "South Africa",
"flag": "ð¿ð¦"
}
]
},
{
"continent": "America",
"countries": [
{
"name": "USA",
"flag": "ðºð¸"
},
{
"name": "Brazil",
"flag": "ð§ð·"
},
{
"name": "Mexico",
"flag": "ð²ð½"
},
{
"name": "Colombia",
"flag": "ð¨ð´"
},
{
"name": "Argentina",
"flag": "ð¦ð·"
}
]
},
{
"continent": "Asia",
"countries": [
{
"name": "China",
"flag": "ð¨ð³"
},
{
"name": "India",
"flag": "ð®ð³"
},
{
"name": "Indonesia",
"flag": "ð®ð©"
},
{
"name": "Pakistan",
"flag": "ðµð°"
},
{
"name": "Bangladesh",
"flag": "ð§ð©"
}
]
}
]
output ::
In SearchBox.render, build up the list of countries from this.state.sourceData
const selectBox2 = this.state.sourceData.map(option => <li>{option.continent}</li>);
return (
<React.Fragment>
<h2>Step 1</h2>
<h3>Select a continent.</h3>
{searhBox}
{selectBox2 && <ul>{selectBox2}</ul>}
</React.Fragment>
);
Also, remember to set an initial value for sourceData in SearchBox.state.
state = {
value: '',
sourceData: []
};