I am trying to take a users input and then use it to get info from an api in react.
my api url is as follows: https://api.dictionaryapi.dev/api/v2/entries/en/${word}
So I want the user input to correspond to ${word}. I have tried countless attempts with failure. I was able to find a solution with JS and HTML, but using react and type script has me very confused. I am completely new to coding.
heres the code i tried and it works. I just need to translate this into my React.
JS file:
async function getDefinition(word) {//to get inputted words
try {
const url = `https://api.dictionaryapi.dev/api/v2/entries/en/${word}`;
const response = await fetch(url);
const defined = await response.json();
return defined;
}
catch (error) {
console.log("Error:", error.message)
}
}
document.getElementById("form").addEventListener("submit", async (event) =>
{
event.preventDefault();
const word = document.getElementById('string').value;
const defined = await getDefinition(word);
console.log(defined[0].meanings[1].definitions);
});
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>words</title>
<link href="styles.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-
awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<script type="module"></script>
</head>
<body>
<header class="header">
<form id="form">
<label for="string">Search for a definition</label>
<input id="string" placeholder="Enter word..." type="string">
<button class="fa fa-search" type="submit"></button>
</form>
</header>
Firstly, you need a state to store the word that you want to search in the API.
Secondly, the handleSubmit
function that will be used to trigger the API.
import { useState } from "react";
export default function App() {
const [text, setText] = useState();
const [searchResult, setSearchResult] = useState();
const handleSubmit = () => {
fetch(`https://api.dictionaryapi.dev/api/v2/entries/en/${text}`)
.then((response) => response.json())
.then((data) => setSearchResult(data));
};
return (
<div className="App">
<label for="string">Search for a definition</label>
<input
id="string"
placeholder="Enter word..."
type="string"
onChange={(event) => setText(event.target.value)}
></input>
<button class="fa fa-search" type="submit" onClick={handleSubmit}>
Submit
</button>
</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.