'React, display results from backend when correct input is given on form frontend
I am working on a project that allows a user to input a variable like ‘username’ or ‘age’ on the form. This is sent to the backend (flask) and the values for ‘username’ should be displayed on the front end. This is my react code currently the app.js and the form.js and an example of my flask code app.py with the json data. Sorry if I’ve explained this badly I’m quite new to this and I appreciate any help!
form.js:
import React, { useState, useEffect } from 'react'
function Users(props) {
return <li>{props.value}</li>;}
function App() {
const [username, setMessage] = useState([])
useEffect(() => {
fetch("/users")
.then((res) => res.json())
.then((data) => {
setMessage(data.username);
});
}, []);
const users = username.map((name) =>
<Users key={name.toString()} value={name} /> );
const handleChange = (e) => {
setMessage({
username,
[e.target.name]: e.target.value()
});
};
const handleSubmit = (e) => {
e.preventDefault()
console.log(users);
};
return (
<div>
<label>
Username
<input
type="text"
name="users"
onChange={handleChange} />
</label>
<br />
<button
onClick={handleSubmit}>Submit</button>
</div>
);
}
export default App
app.js:
import React from 'react'
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'
import form from './components/form'
import './App.css'
export default function App() {
return (
<Router>
<div>
<Switch>
<Route path="/data" component={ data } />
</Switch>
</div>
</Router>
)
}
app.py:
from flask import Flask, render_template, request
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.route('/users')
def get_users():
return {"username" : ["ben123", "amy321"]
}
app.run(host='localhost', port=5000)
if __name__ == "__main__":
app.run(debug=True)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
