Reputation: 171
I have a problem, when I try to pass a .json like this: this is my class
import MyForm from './MyForm';
class CreateProject extends React.Component{
constructor(){
super();
this.state = { categories:[]}
}
getCategories(){
API.get(`/categories/public`)
.then(resp=>{
this.setState({categories: resp.data})
})
.catch(err => {
console.log(err)
})
}
ComponentDidMOunt(){
// here show me the API correct like this
// 0:{id:1, name:"categorie one"}
// 1:{id:11, name:"categorie four"}
// 2:{id:19, name:"categorie five"}
// 3:{id:16, name:"categorie six"}
this.getCategories()
}
render(){
return(<div> <MyForm categories={this.state.categories}/></div>)
}
}
my functional component
export const MyForm = ({categories}) =>{
return(
<div>
<select >
{ // here not working because .map not belong a function categories
categories.map(category =>(
<option value={category.id}>{category.name}</option>
))
}
</select>
</div>)
}
how to read a categories inside my functional component using a loop . please something suggestion or a tip thanks for your attention.
Upvotes: 1
Views: 1925
Reputation: 2597
A couple things I noticed
componentDidMount()
spelling error and an incorrect import. Should be:
import { MyForm } from './MyForm'
Here's a very similar working example. I'm just using a different api and I have an async function, also added some null checks on categories (might be redundant?).
https://codesandbox.io/s/modern-frog-0wmyu
import React from "react";
import { MyForm } from "./my-form";
class CreateProject extends React.Component {
constructor() {
super();
this.state = { categories: [] };
}
async getCategories() {
const response = await fetch(`https://jsonplaceholder.typicode.com/posts`);
const data = await response.json();
this.setState({ categories: data });
}
componentDidMount() {
// here show me the API correct like this
// 0:{id:1, name:"categorie one"}
// 1:{id:11, name:"categorie four"}
// 2:{id:19, name:"categorie five"}
// 3:{id:16, name:"categorie six"}
this.getCategories();
}
render() {
const { categories } = this.state;
return (
<div>
{categories && categories.length > 0 && (
<MyForm categories={categories} />
)}
</div>
);
}
}
export default CreateProject;
MyForm component
import React from "react";
// I'm using the title property, but for your API it should be category.name
export const MyForm = ({ categories }) => (
<select>
{categories &&
categories.map(category => (
<option value={category.id}>{category.title}</option>
))}
</select>
);
Upvotes: 2