auto complete React - javascript

When selecting one of the movies, I need to set a state "year" with the year of the selected movie. how do I do?
For example, when pressing 'The Godfather' I need to perform the set state of the state 'year' with the value 1972.
import * as React from 'react';
import TextField from '#mui/material/TextField';
import Autocomplete from '#mui/material/Autocomplete';
export default function ComboBox() {
const [year, setYear] = React.useState(false);
return (
<Autocomplete
disablePortal
id="combo-box-demo"
options={top100Films}
sx={{ width: 300 }}
renderInput={(params) => <TextField {...params} label="Movie" />}
/>
);
}
const top100Films = [
{ label: 'The Shawshank Redemption', year: 1994 },
{ label: 'The Godfather', year: 1972 },
{ label: 'The Godfather: Part II', year: 1974 },
{ label: 'The Dark Knight', year: 2008 }
];

Related

Error in the values of the Rechart Stacked chart

I'm trying to build a Stacked Bar Chart using the Pchart library. I attach the code below.
function StackedBarChart({...props}){
const {dataChart:{data,keys}} = props;
const renderBars = () =>{
return keys.map((item,index)=>(
<Bar
key={index}
dataKey={item}
stackId='a'
fill={index%2?'blue':'red'}
label
/>
))
}
return(
<ResponsiveContainer width='100%' height={400}>
<BarChart
data={data}
stackOffset='expand'
>
<XAxis dataKey="name" />
<YAxis />
{renderBars()}
</BarChart>
</ResponsiveContainer>
)
}
When I output a value to each Bar I get incorrect signatures. . Why is 2 Bar subscribed with the value 1 and not the remaining percentage. What is my mistake ?
my data
const dataChart = {
data: [{
name: 'Page A',
count: 4000,
price: 2400,
},
{
name: 'Page B',
count: 3000,
price: 1398,
},
{
name: 'Page C',
count: 2000,
price: 9800,
},
],
keys: ['price', 'count']
};
The reason of this behavior, is that upper bar shown his top value, which is 1, so this is the sum of all bars stacked.
To avoid this situation I used valueAccessor and some formatting to get value of bar and count its percentage.
Here is a link to working codesandbox where you can see final result

Dynamic Bar Labeling on Ant Design Charts

I'm trying to create an ant design chart with some custom labels on the bars based on what data they contain. Is it possible to do this dynamically? I want the labels to say "Water" and "Land", which is the type of each respective data. Here is my code which I'm playing around in the Ant Design Charts Sandbox
import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';
import { Bar } from '#ant-design/plots';
const DemoBar = () => {
const data = [
{
year: '1991',
value: 3,
type: 'Water',
},
{
year: '1991',
value: 4,
type: 'Land',
},
];
const config = {
data: data.reverse(),
isStack: true,
xField: 'value',
yField: 'year',
seriesField: 'type',
legend: false,
label: {content: data[0].type}, // How can the content link to the data?
interactions: [{ type: 'tooltip', enable: false }]
};
return <Bar {...config} />;
};
ReactDOM.render(<DemoBar />, document.getElementById('container'));
I figured it out: Javascript lets you create a function here. Replacing the label line with this line solved it:
label: {content: ({ type }) => { return type },},
For typescript the line is:
label: { content: ({ type }: any) => { return type }, },

Creating a ref to Line chart using react-chartjs-2

I'm trying to create a ref to the chart I'm building with chart.js and react-chartjs-2.
Here's the line where I'm trying to create the ref specifying the type: const chartRef = useRef<Line>(null);
And this is the error I get:
'Line' refers to a value, but is being used as a type here. Did you mean 'typeof Line'?
I found the following documentation but since I'm new to TypeScript I don't know how to interpret it yet. Here's the complete code I'm using:
import { Line } from "react-chartjs-2";
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend
} from "chart.js";
import { useRef } from "react";
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend
);
export const data = {
labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
datasets: [
{
label: "First dataset",
data: [33, 53, 85, 41, 44, 65],
fill: true,
backgroundColor: "rgba(75,192,192,0.2)",
borderColor: "rgba(75,192,192,1)"
},
{
label: "Second dataset",
data: [33, 25, 35, 51, 54, 76],
fill: false,
borderColor: "#742774"
}
]
};
export default function App() {
const chartRef = useRef<Line>(null);
return (
<div className="App">
<h1>This is a chart.</h1>
<Line data={data} ref={chartRef} />
</div>
);
}
Can you point me in the right direction? Thanks!
I'm not terribly familiar with ChartJS, but when I changed your existing code from const chartRef = useRef<Line>(null); to const chartRef = useRef<'line'>(null); (per the docs), the linter gave me a better idea as to the what needed to be fixed (on the ref).
In your case:
export function App() {
const chartRef = useRef<ChartJS<"line", number[], string>>(null);
return (
<div className="App">
<h1>This is a chart.</h1>
<Line data={data} ref={chartRef} />
</div>
);
}
Working CodeSandbox

Cannot read properties of undefined with react-chartjs-2 and chart js problem

When I want to use react chartjs it is giving me these errors
The version I use for chart.js is ^3.5.0 and ^4.0.1 for react-chartjs-2
I downgrade it to version 2 but it didn't work
Chart component codes
import React from 'react'
import { Bar } from 'react-chartjs-2'
import { Chart as ChartJS } from 'chart.js/auto'
function Chart({ chartData }) {
return <Bar data={chartData} />
}
export default Chart
Main component
const [data, setData] = useState({
labels: UserData.map((data) => data.year),
datasets: [
{
label: 'Users Gained',
data: UserData.map((data) => data.userGain),
},
],
})
<Chart chartData={data} />
Data
export const UserData = [
{
id: 1,
year: 2016,
userGain: 80000,
userLost: 823,
},
{
id: 2,
year: 2017,
userGain: 45677,
userLost: 345,
},
{
id: 3,
year: 2018,
userGain: 78888,
userLost: 555,
},
{
id: 4,
year: 2019,
userGain: 90000,
userLost: 4555,
},
{
id: 5,
year: 2020,
userGain: 4300,
userLost: 234,
},
]
in Main component:
import { UserData } from './UserData.js';
import React from 'react'
const [data, setData] = React.useState({
labels: UserData?.map((data) => data.year),
datasets: [
{
label: 'Users Gained',
data: UserData?.map((data) => data.userGain),
},
],
})
<Chart chartData={data} />
The problem may be related to the way you import/read the UserData. Assuming the data is defined in UserData.js, you could import it as follows:
import { UserData } from './UserData.js';
Please take a look at this StackBlitz and see how it could work with your code.

Check if value is undefined before render React Native

I am using (Drop Down Picker library) to display categories of my data which I get from api call. I am waiting for api to fetch the data and then plan to display the categories. The problem is that I need to reformat data first and use hooks before render, but I can't get it right.
how does the data for picker looks like:
items={[
{label: 'USA', value: 'usa'},
{label: 'UK', value: 'uk'},
{label: 'France', value: 'france'/>},
]}
my hooks:
const [country, setCountry] = useState("0");
const [categoryData, setCategoryData] = useState();
const [testingCategories, setTestingCategories] = useState({
label: null,
value: null,
});
my effect hooks and reformatting the data:
//this hook calls api and sets the data to categories data of my type
useEffect(() => {
getData(api.API_GET_DEPS, setIsLoading, setCategoryData);
}, []);
//this hooks reformats the data into acceptable format for picker
useEffect(() => {
setTestingCategories(
categoryData
? categoryData.map((item) => ({
label: item.DEPNAME, //label
value: item.DEPID, //value
}))
: [{ label: null, value: null }]
);
}, [categoryData]);
my render of drop down:
<View style={styles.container}>
{testingCategories ? (
<DropDownPicker
dropDownMaxHeight={300}
placeholder="All"
defaultValue={country}
items={testingCategories}
containerStyle={{ height: 50 }}
style={{ backgroundColor: "#fafafa" }}
itemStyle={{
justifyContent: "flex-start",
}}
dropDownStyle={{ backgroundColor: "#fafafa" }}
onChangeItem={(item) => {
console.log("changed");
}}
onOpen={() => setContainerOpacity(0.1)}
onClose={() => setContainerOpacity(1)}
labelStyle={{
fontSize: 16,
color: colors.dark,
fontWeight: "600",
}}
arrowSize={25}
arrowColor={colors.dark}
/>
) : (
<></>
)}
I get an error that drop down picker can't match the defaultValue with any label in testingCategories because it is null and haven't loaded yet. I suppose I am using setter wrong because I can't check whether testingCategories's first element was loaded. What am I doing wrong?
You have a typing mismatch between your useState definition and where you use setTestingCategories later.
In your useState, you define the initial value as a singular object:
useState({
label: null,
value: null,
});
However, what you probably want is an empty array:
useState([]);
I would also change your current line [{ label: null, value: null }] to just be an empty array [].
Then, your testingCategories flag will work, because testingCategories will initially be an array of length 0, which will fail the truthiness test.

Categories

Resources