I'm building an application based on user survey in React JS.
All the questions are coming from API as JSON response
const data = {
preQuestions: {
landingPage: {
heading: 'This is the ladning page',
buttons: {
yesButton: {
text: 'yes',
action: '1A',
},
noButton: {
text: 'No',
action: '1B',
},
},
},
'1A': {
heading: 'This is the 1A Component',
buttons: {
yesButton: {
text: 'yes',
action: '1C',
},
noButton: {
text: 'No',
action: '1D',
},
},
},
'1B': {
heading: 'This is the 1B Component',
buttons: {
yesButton: {
text: 'yes',
action: '1C',
},
noButton: {
text: 'No',
action: '1D',
},
},
},
'1C': {
heading: 'This is the 1C Component',
buttons: {
yesButton: {
text: 'yes',
action: '1A',
},
noButton: {
text: 'No',
action: '1B',
},
},
},
'1D': {
heading: 'This is the 1D Component',
buttons: {
yesButton: {
text: 'yes',
action: '1B',
},
noButton: {
text: 'No',
action: '1C',
},
},
},
},
};
I wanted to display only 1st question by default and based on the user response I need to load the second question on same page, where use can able to see the previous question .
Basically I wanted to stack all the questions one below the other based on user actions.
But current with my logic, When user selects the next question, prev question getting disappeared.
Below is my code,
const [active, setActive] = React.useState<any>(
data.preQuestions['landingPage']
);
const content = data.preQuestions;
const loadNextCompnent = (actionId) => {
setActive(actionId);
};
const renderQustionComponent = () => {
Previous question
return (
<div>
<h1>{active?.heading}</h1>
<button
onClick={() =>
loadNextCompnent(content[active?.buttons?.yesButton?.action])
}
>
{active.buttons.yesButton.text}{' '}
</button>
<button
onClick={() =>
loadNextCompnent(content[active?.buttons?.noButton?.action])
}
>
{active.buttons.noButton.text}{' '}
</button>
</div>
);
};
return <div>{renderQustionComponent()}</div>;
How Can I stack all the questions one below the other ? Please help.
Working Stackblitz link https://stackblitz.com/edit/react-ts-z8clfj
Related
I've created a React table, and I have a data in Elasticsearch. I have successfully fetched data from Elasticsearch using API(fetch) call; this data is being displayed in the console but not in screen. How to solve this problem?
this code will fetch data from Elasticsearch, then display it on React Table.
import './App.css';
import Table from './pages/Table';
import { useEffect, useState } from 'react';
function App() {
const [dataTable, setDataTable] = useState([]);
// this is our JOSN data to be displayed in the console
var myHeaders = new Headers();
myHeaders.append("Authorization", "Basic xxcxxxxxxxxx==");
myHeaders.append("Content-Type", "application/json");
var requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow'
};
// this is fetching data from Elastic and working successfully
useEffect(() => {
fetch("https://192.168.1.3:9200/myapp/_doc/1", requestOptions)
.then(response => response.json())
.then(result => setDataTable(result.data)) // the error comes here
.catch(error => console.log('error', error));
}, []);
console.log(dataTable);
const column = [
{ heading: 'Id', value: '_index' },
{ heading: 'Index', value: '_index' },
{ heading: 'Score', value: '_score' },
{ heading: 'Timestamp', value: '#timestamp' },
{ heading: 'Version', value: '#version' },
{ heading: 'Ephemeral Id', value: 'agent.ephemeral_id' },
{ heading: 'Agent Id', value: 'agent.id' },
{ heading: 'Agent name', value: 'agent.name' },
{ heading: 'Agent type', value: 'agent.type' },
{ heading: 'Agent Version', value: 'agent.version' },
{ heading: 'esc version', value: 'esc.version' },
{ heading: 'event original', value: 'event.original' },
{ heading: 'host architecture', value: 'host.architecture' },
{ heading: 'host hostname', value: 'host.hostname' },
{ heading: 'host id', value: 'host.id' },
{ heading: 'host ip', value: 'host.ip' },
{ heading: 'host mac', value: 'host.mac' },
{ heading: 'host name', value: 'host.name' },
{ heading: 'host os build', value: 'host.os.build' },
{ heading: 'host os family', value: 'host.os.family' },
{ heading: 'host os kernel', value: 'host.os.kernel' },
{ heading: 'host os name', value: 'host.os.name' },
{ heading: 'host os platform', value: 'host.os.platform' },
{ heading: 'host os type', value: 'host.os.type' },
{ heading: 'host os version', value: 'host.os.version' },
{ heading: 'input type', value: 'input.type' },
{ heading: 'log file path', value: 'log.file.path' },
{ heading: 'log offset', value: 'log.offset' },
{ heading: 'message', value: 'message' },
{ heading: 'tags', value: 'tags' },
]
// console.log(column)
return (
<div className="App" >
<h1>eSafe Table</h1>
<Table data={dataTable} column={column} />
</div>
);
}
export default App;
I have a react native component that has flatlist of 20 items (Data). The item contains component which uses setTimeout. Would this cause any performance
handleSpinner = result => {
setTimeout(() => {
// handle task
}, 3000);
return<some stuff></some>
};
const DATA = [
{
id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba',
title: 'First Item',
},
{
id: '3ac68afc-c605-48d3-a4f8-fbd91aa97f63',
title: 'Second Item',
},
{
id: '58694a0f-3da1-471f-bd96-145571e29d72',
title: 'Third Item',
},
//...MORE ITEMS
];
<FlatList
keyExtractor={this.keyExtractor}
data={list}
renderItem={this.handleSpinner}
It will cause the serious problem when there are lots of data in the list.
I'd like to be able to render a React Component inside of a HighCharts Graph. I'd like to render the component DatePicker inside my HighCharts Graph, rather than being above it like it currently is? I'm using the HighCharts Official React Wrapper, and this is what my code looks like:
function Graph(props) {
const [startDate, setStartDate] = useState(new Date('1969-11-19 PST'));
const [bx, setBx] = useState([]);
const [by, setBy] = useState([]);
const [bz, setBz] = useState([]);
async function getData(table, year, month, day) {
...
}
useEffect(() => {
...
}, [startDate])
var options = {
chart: {
events: {
load: function() {
this.showLoading();
setTimeout(this.hideLoading.bind(this), 2000);
}
}
},
lang: {
noData: "Awaiting for data"
},
rangeSelector: {
inputEnabled: false,
buttons: [
{
type: 'all',
text: '1d',
title: 'View 1 Day'
},
{
type: 'minute',
count: 10,
text: '10m',
title: 'View 10 minutes'
},
{
type: 'minute',
count: 1,
text: '1m',
title: 'View 1 minutes'
},
{
type: 'second',
count: 30,
text: '30s',
title: 'View 30 seconds'
},
]
},
chart: {
zoomType: 'x'
},
title: {
text: props.title
},
xAxis: {
type: 'datetime'
},
time: {
timezoneOffset: 8*60
},
series: [
{
marker: {
enabled: true,
radius: 2
},
color: 'red',
name: 'Bx',
pointStart: startDate.getTime(),
pointInterval: 1000,
data: bx // data has to be [x, y] pairs
},
{
marker: {
enabled: true,
radius: 2
},
color: 'blue',
name: 'By',
pointStart: startDate.getTime(),
pointInterval: 1000,
data: by
},
{
marker: {
enabled: true,
radius: 2
},
color: 'green',
name: 'Bz',
pointStart: startDate.getTime(),
pointInterval: 1000,
data: bz
}
]
}
const isValidDate = (date) => {
date.getTime();
const origDate = new Date('1969-11-19 PST');
const finalDate = new Date('1970-04-03 PST');
console.log("GET DATE", date.getTime()) // getting number day of month
const bool = origDate.getTime() <= date.getTime() && date.getTime() <= finalDate.getTime();
return bool;
}
return (
<React.Fragment>
<DatePicker
selected={startDate}
filterDate={isValidDate}
onChange={(date) => setStartDate(date)}
/>
<HighchartsReact
highcharts={Highcharts}
constructorType={'stockChart'}
options={options}
/>
</React.Fragment>
);
}
I see this example from the HighCharts React Official Wrapper Github, but I'm still a bit confused by it and am wondering if I could simply do the same thing with a functional component. https://codesandbox.io/s/1o5y7r31k3
I've made a codesandbox of my code here https://codesandbox.io/s/friendly-moon-y8guc
I'm working on a todo list in my current project.
I can display the todo list but when I click the checkbox to mark a task as complete I get this TypeError:
I've tried to use Google and Stack to find an answer but still can't figure out what it is I'm doing wrong. Why is toggleComplete not a function?
Reducer / todosOne.js
import { createSlice } from '#reduxjs/toolkit'
export const todosOne = createSlice({
name: 'todos',
initialState: [
{ id: 1, text: 'This is a todo item', complete: false },
{ id: 2, text: 'This is a todo item', complete: false },
{ id: 3, text: 'This is a todo item', complete: false },
{ id: 4, text: 'This is a todo item', complete: false },
{ id: 5, text: 'This is a todo item', complete: false },
],
toggleComplete: (store, action) => {
const checkedItem = store.items.find(item => item.id === action.payload)
if (checkedItem) {
checkedItem.complete = !checkedItem.complete
}
}
})
Component / TodoListOne.js
import React from 'react'
import styled from 'styled-components'
import { useSelector, useDispatch } from 'react-redux'
import { todosOne } from '../Reducers/todosOne'
export const TodoListOne = () => {
const dispatch = useDispatch();
const items = useSelector(store => store.todos);
const onChecked = complete => {
dispatch(todosOne.actions.toggleComplete(complete))
}
return (
<>
{items.map(todos => (
<TodoContainer key={todos.id}>
<List>
<label>
<input type="checkbox"
checked={todos.complete}
onChange={() => onChecked(todos.id)}
/>
</label>
</List>
<TodoText>{todos.text}</TodoText>
</TodoContainer>
))}
</>
)
}
It should be
export const todosOne = createSlice({
name: 'todos',
initialState: [
{ id: 1, text: 'This is a todo item', complete: false },
{ id: 2, text: 'This is a todo item', complete: false },
{ id: 3, text: 'This is a todo item', complete: false },
{ id: 4, text: 'This is a todo item', complete: false },
{ id: 5, text: 'This is a todo item', complete: false },
],
// here!
reducers: {
toggleComplete: (store, action) => {
const checkedItem = store.items.find(item => item.id === action.payload)
if (checkedItem) {
checkedItem.complete = !checkedItem.complete
}
}
// here!
}
})
I have a button that logs an event. When the button is clicked it automatically picks the chosen date from a calendar. after this the user would have to register two boolean attributes. I don't know how to do this efficiently. Can someone help me?
async cadastrarPresenca() {
let ida: boolean;
let volta: boolean;
const alert = await this.alertController.create({
header: 'Confirmar ida e/ou volta',
inputs: [
{
name: 'Ida',
type: 'checkbox',
label: 'Ida',
value: ida,
},
{
name: 'Volta',
type: 'checkbox',
label: 'Volta',
value: volta
}],
buttons: [
{
text: 'Cancel',
role: 'cancel',
cssClass: 'secondary',
handler: () => {
console.log('Confirm Cancel');
}
}, {
text: 'Ok',
handler: () => {
let start = this.dataSelecionada;
let end = this.dataSelecionada;
end.setMinutes(end.getMinutes() + 60);
let presenca = {
title: 'Event #' + start.getMinutes(),
startTime: start,
endTime: end,
allDay: false,
ida: ida,
volta: volta
};
this.firestore.collection('aluno').doc(this.authService.getUsuario().uid).collection('presenca').add(presenca);
}
}
]
});
await alert.present();
You just need to update your ok handler so that the data is passed in and then you can use it:
async cadastrarPresenca() {
let ida: boolean;
let volta: boolean;
const alert = await this.alertController.create({
header: 'Confirmar ida e/ou volta',
inputs: [
{
name: 'Ida',
type: 'checkbox',
label: 'Ida',
value: ida,
},
{
name: 'Volta',
type: 'checkbox',
label: 'Volta',
value: volta
}],
buttons: [
{
text: 'Cancel',
role: 'cancel',
cssClass: 'secondary',
handler: () => {
console.log('Confirm Cancel');
}
}, {
text: 'Ok',
// NEW CODE HERE
handler: (inputData) => {
console.log(inputData);
console.log(inputData["Volta"].checked);
// END OF NEW CODE HERE
let start = this.dataSelecionada;
let end = this.dataSelecionada;
end.setMinutes(end.getMinutes() + 60);
let presenca = {
title: 'Event #' + start.getMinutes(),
startTime: start,
endTime: end,
allDay: false,
ida: ida,
volta: volta
};
this.firestore.collection('aluno').doc(this.authService.getUsuario().uid).collection('presenca').add(presenca);
}
}
]
});
await alert.present();
So the new code is all that I've changed from your snippet:
// NEW CODE HERE
handler: (inputData) => {
console.log(inputData);
console.log(inputData["Volta"].checked);
// END OF NEW CODE HERE
You can look at the code that Ionic is built on for reference to see what options should be available, or just check out the first console.log I added.