Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React js Typescript string array variable

I have the following two components. I think I'm having trouble properly declaring my array object to match the interface I've declared. Why do I get the following error on all my properties?

[0] (10,5): error TS2304: Cannot find name 'color'.
[0] (11,5): error TS2304: Cannot find name 'id'.

app.tsx

import * as React from "react";
import * as ReactDOM from "react-dom";

const cars = [
    { id: 1, make: "Make1",  year: 2016, color: "black" },
    { id: 2, make: "Make2",  year: 2006, color: "gray" },
    { id: 3, make: "Make3",  year: 2012, color: "purple" },
];

ReactDOM.render(<CarTool cars={cars} />, document.querySelector("main"));

Car Component

import * as React from "react";    
import * as ReactDOM from "react-dom";

interface CarProps {
    cars: string[];
}    

export class Car extends React.Component<CarProps, void> {
    public render() {
        return <div>
            <h1>Car Tool</h1>
            <table>
                <thead>
                    <tr>
                        <td>Make</td>
                        <td>Year</td>
                        <td>Color</td>
                    </tr>
                </thead>
                <tbody>
                    {this.props.cars.map((car) => <tr><td>car.make</td></tr>)}
                </tbody>
            </table>
        </div>;
    }
}
like image 273
mo_maat Avatar asked Aug 04 '17 04:08

mo_maat


People also ask

How do you declare an array of strings in React?

To type the useState hook as an array of strings in React, use the hook's generic, e.g. const [names, setNames] = useState<string[]>([]) . The state variable can be initialized to an empty array or an array of strings and will only accept string values. Copied!

How do you define a string array in TypeScript?

An array in TypeScript can contain elements of different data types using a generic array type syntax, as shown below. let values: (string | number)[] = ['Apple', 2, 'Orange', 3, 4, 'Banana']; // or let values: Array<string | number> = ['Apple', 2, 'Orange', 3, 4, 'Banana'];

How do you pass an array as a prop in React TypeScript?

To pass an array as a prop to a component in React, wrap the array in curly braces, e.g. <Books arr={['A', 'B', 'C']} /> . The child component can perform custom logic on the array or use the map() method to render the array's elements. Copied!


1 Answers

It's because you've declared you props type as string[]

Declare the interface for your object

interface Car
{
    id: number, 
    make: string,
    year: number,
    color: string,
}

And then declare you props as

interface CarProps {
    cars: Car[];
}
like image 138
hendrixchord Avatar answered Oct 10 '22 16:10

hendrixchord