In my code I have it so the user can search for the type of Pokémon they want and when the user submits it, I want to send it to another component to display all the information. The issue is the data isn't passing through to the other component I'm pretty new to react so I might be missing something obvious. This is the component that retrieves the data from the api.
const Search = () => {
const [inputValue, setInputValue] = useState("");
const [userData, setUserData] = useState([]);
const userInput = (e) => {
setInputValue(e.target.value);
};
const handleClick = (e) => {
e.preventDefault();
apiCall(inputValue);
};
const apiCall = async (name) => {
const url = `https://pokeapi.co/api/v2/pokemon/${name}`;
const response = await fetch(url);
const data = await response.json();
setUserData(data);
};
return (
<div>
<button className="btn" onClick={handleClick}>
Search
</button>
<input
type="search"
onChange={userInput}
value={inputValue}
placeholder="Enter your pokemon name"
className="btn-search"
></input>
<div>
<PokiApi props={userData} />
</div>
</div>
);
};
This is the component that I want to display the api data to the page.
export default class PokiApi extends React.Component {
constructor(props) {
super(props);
this.state = {
data: props.props,
};
}
render() {
return (
<div>
<div>
<div>{this.state.data}</div>
</div>
</div>
);
}
}
Try this:
const PokiApi({props}) {
return (
<div>
<div>
<div>{props}</div>
</div>
</div>
);
}
the props in the function component will be userData and props.props is undefined
This
is what you need
const Search = () => {
const [inputValue, setInputValue] = useState('');
const [userData, setUserData] = useState();
const userInput = (e) => {
setInputValue(e.target.value);
};
const apiCall = async (name) => {
const url = `https://pokeapi.co/api/v2/pokemon/${name}`;
const response = await fetch(url);
const data = await response.json();
setUserData(data);
};
const handleSubmit = (e) => {
e.preventDefault();
apiCall(inputValue);
};
return (
<div>
<form action='' onSubmit={handleSubmit}>
<button className='btn'>Search</button>
<input type='search' onChange={userInput} value={inputValue} placeholder='Enter your pokemon name' className='btn-search' />
</form>
<div>
<PokiApi data={userData} />
</div>
</div>
);
};
const PokiApi = ({ data }) => {
// data is an array
if (!data) {
return <div>Enter pokemon to get the data</div>;
}
return (
<div>
<h1>{data.name}</h1>
</div>
);
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.