In a React component for a <select> menu, I need to set the selected attribute on the option that reflects the application state.
In render(), the optionState is passed from the state owner to the SortMenu component. The option values are passed in as props from JSON.
render: function() {
var options = [],
optionState = this.props.optionState;
this.props.options.forEach(function(option) {
var selected = (optionState === option.value) ? ' selected' : '';
options.push(
<option value={option.value}{selected}>{option.label}</option>
);
});
// pass {options} to the select menu jsx
However that triggers a syntax error on JSX compilation.
Doing this gets rid of the syntax error but obviously doesn't solve the problem:
var selected = (optionState === option.value) ? 'selected' : 'false';
<option value={option.value} selected={selected}>{option.label}</option>
I also tried this:
var selected = (optionState === option.value) ? true : false;
<option value={option.value} {selected ? 'selected' : ''}>{option.label}</option>
Is there a recommended way of solving this?
React makes this even easier for you. Instead of defining selected on each option, you can (and should) simply write value={optionsState} on the select tag itself:
<select value={optionsState}>
<option value="A">Apple</option>
<option value="B">Banana</option>
<option value="C">Cranberry</option>
</select>
For more info, see the React select tag doc.
Also, React automatically understands booleans for this purpose, so you can simply write (note: not recommended)
<option value={option.value} selected={optionsState == option.value}>{option.label}</option>
and it will output 'selected' appropriately.
You could do what React warns you when you try to set the "selected" property of the <option>:
Use the defaultValue or value props on <select> instead of setting selected on <option>.
So, you can use options.value on the defaultValue of your select
Here is a complete solution which incorporates the best answer and the comments below it (which might help someone struggling to piece it all together):
UPDATE FOR ES6 (2019) - using arrow functions and object destructuring
in main component:
class ReactMain extends React.Component {
constructor(props) {
super(props);
this.state = { fruit: props.item.fruit };
}
handleChange = (event) => {
this.setState({ [event.target.name]: event.target.value });
}
saveItem = () => {
const item = {};
item.fruit = this.state.fruit;
// do more with item object as required (e.g. save to database)
}
render() {
return (
<ReactExample name="fruit" value={this.state.fruit} handleChange={this.handleChange} />
)
}
}
included component (which is now a stateless functional):
export const ReactExample = ({ name, value, handleChange }) => (
<select name={name} value={value} onChange={handleChange}>
<option value="A">Apple</option>
<option value="B">Banana</option>
<option value="C">Cranberry</option>
</select>
)
PREVIOUS ANSWER (using bind):
in main component:
class ReactMain extends React.Component {
constructor(props) {
super(props);
// bind once here, better than multiple times in render
this.handleChange = this.handleChange.bind(this);
this.state = { fruit: props.item.fruit };
}
handleChange(event) {
this.setState({ [event.target.name]: event.target.value });
}
saveItem() {
const item = {};
item.fruit = this.state.fruit;
// do more with item object as required (e.g. save to database)
}
render() {
return (
<ReactExample name="fruit" value={this.state.fruit} handleChange={this.handleChange} />
)
}
}
included component (which is now a stateless functional):
export const ReactExample = (props) => (
<select name={props.name} value={props.value} onChange={props.handleChange}>
<option value="A">Apple</option>
<option value="B">Banana</option>
<option value="C">Cranberry</option>
</select>
)
the main component maintains the selected value for fruit (in state), the included component displays the select element and updates are passed back to the main component to update its state (which then loops back to the included component to change the selected value).
Note the use of a name prop which allows you to declare a single handleChange method for other fields on the same form regardless of their type.
I was making a drop-down menu for a language selector - but I needed the dropdown menu to display the current language upon page load. I would either be getting my initial language from a URL param example.com?user_language=fr, or detecting it from the user’s browser settings. Then when the user interacted with the dropdown, the selected language would be updated and the language selector dropdown would display the currently selected language.
Since this whole thread has been giving fruit examples, I got all sorts of fruit goodness for you.
First up, answering the initially asked question with a basic React functional component - two examples with and without props, then how to import the component elsewhere.
Next up, the same example - but juiced up with Typescript.
Then a bonus finale - A language selector dropdown component using Typescript.
Basic React (16.13.1) Functional Component Example. Two examples of FruitSelectDropdown , one without props & one with accepting props fruitDetector
import React, { useState } from 'react'
export const FruitSelectDropdown = () => {
const [currentFruit, setCurrentFruit] = useState('oranges')
const changeFruit = (newFruit) => {
setCurrentFruit(newFruit)
}
return (
<form>
<select
onChange={(event) => changeFruit(event.target.value)}
value={currentFruit}
>
<option value="apples">Red Apples</option>
<option value="oranges">Outrageous Oranges</option>
<option value="tomatoes">Technically a Fruit Tomatoes</option>
<option value="bananas">Bodacious Bananas</option>
</select>
</form>
)
}
Or you can have FruitSelectDropdown accept props, maybe you have a function that outputs a string, you can pass it through using the fruitDetector prop
import React, { useState } from 'react'
export const FruitSelectDropdown = ({ fruitDetector }) => {
const [currentFruit, setCurrentFruit] = useState(fruitDetector)
const changeFruit = (newFruit) => {
setCurrentFruit(newFruit)
}
return (
<form>
<select
onChange={(event) => changeFruit(event.target.value)}
value={currentFruit}
>
<option value="apples">Red Apples</option>
<option value="oranges">Outrageous Oranges</option>
<option value="tomatoes">Technically a Fruit Tomatoes</option>
<option value="bananas">Bodacious Bananas</option>
</select>
</form>
)
}
Then import the FruitSelectDropdown elsewhere in your app
import React from 'react'
import { FruitSelectDropdown } from '../path/to/FruitSelectDropdown'
const App = () => {
return (
<div className="page-container">
<h1 className="header">A webpage about fruit</h1>
<div className="section-container">
<h2>Pick your favorite fruit</h2>
<FruitSelectDropdown fruitDetector='bananas' />
</div>
</div>
)
}
export default App
FruitSelectDropdown with Typescript
import React, { FC, useState } from 'react'
type FruitProps = {
fruitDetector: string;
}
export const FruitSelectDropdown: FC<FruitProps> = ({ fruitDetector }) => {
const [currentFruit, setCurrentFruit] = useState(fruitDetector)
const changeFruit = (newFruit: string): void => {
setCurrentFruit(newFruit)
}
return (
<form>
<select
onChange={(event) => changeFruit(event.target.value)}
value={currentFruit}
>
<option value="apples">Red Apples</option>
<option value="oranges">Outrageous Oranges</option>
<option value="tomatoes">Technically a Fruit Tomatoes</option>
<option value="bananas">Bodacious Bananas</option>
</select>
</form>
)
}
Then import the FruitSelectDropdown elsewhere in your app
import React, { FC } from 'react'
import { FruitSelectDropdown } from '../path/to/FruitSelectDropdown'
const App: FC = () => {
return (
<div className="page-container">
<h1 className="header">A webpage about fruit</h1>
<div className="section-container">
<h2>Pick your favorite fruit</h2>
<FruitSelectDropdown fruitDetector='bananas' />
</div>
</div>
)
}
export default App
Bonus Round: Translation Dropdown with selected current value:
import React, { FC, useState } from 'react'
import { useTranslation } from 'react-i18next'
export const LanguageSelectDropdown: FC = () => {
const { i18n } = useTranslation()
const i18nLanguage = i18n.language
const [currentI18nLanguage, setCurrentI18nLanguage] = useState(i18nLanguage)
const changeLanguage = (language: string): void => {
i18n.changeLanguage(language)
setCurrentI18nLanguage(language)
}
return (
<form>
<select
onChange={(event) => changeLanguage(event.target.value)}
value={currentI18nLanguage}
>
<option value="en">English</option>
<option value="de">Deutsch</option>
<option value="es">Español</option>
<option value="fr">Français</option>
</select>
</form>
)
}
An invaluable resource for React/Typescript
Here is the latest example of how to do it. From react docs, plus auto-binding "fat-arrow" method syntax.
class FlavorForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: 'coconut'};
}
handleChange = (event) =>
this.setState({value: event.target.value});
handleSubmit = (event) => {
alert('Your favorite flavor is: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Pick your favorite flavor:
<select value={this.state.value} onChange={this.handleChange}>
<option value="grapefruit">Grapefruit</option>
<option value="lime">Lime</option>
<option value="coconut">Coconut</option>
<option value="mango">Mango</option>
</select>
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
Main Point - Controlled Component
You are looking to set up a "Controlled Component". This will require you to set the value on the element as well as handle the on change event to update the value.
https://reactjs.org/docs/forms.html#controlled-components
Examples
https://codepen.io/codyswartz/pen/QWqYNrY
Simple Functional Component Select Example
This also includes a default and grays it out.
const defaultSelectValue = "Select a fruit"
const SelectExample = () => {
const [selected, setSelected] = useState(defaultSelectValue)
return (
<>
<label htmlFor="fruits">Fruits</label>{' '}
<select
id="fruits"
name="fruits"
defaultValue={selected}
style={{ color: selected === defaultSelectValue ? "gray" : "black" }}
onChange={e => setSelected(e.target.value)}
>
<option>{defaultSelectValue}</option>
<option>Banana</option>
<option>Apple</option>
<option>Orange</option>
</select>
<h2>Selected: {selected}</h2>
</>
)
}
// Usage
<SelectExample />
Dynamic Reusable Example with Default
This would take a collection of strings using the first as a default.
const SelectExample = ({ name, items }) => {
const defaultSelectValue = items[0]
const [selected, setSelected] = useState(defaultSelectValue)
return (
<>
<label htmlFor={name}>{name}</label>{' '}
<select
id={name}
name={name}
defaultValue={selected}
style={{ color: selected === defaultSelectValue ? "gray" : "black" }}
onChange={e => setSelected(e.target.value)}
>
{items.map(item => (
<option key={item} value={item}>
{item}
</option>
))}
</select>
<h2>Selected: {selected}</h2>
</>
)
}
// Usage
<SelectExample
name="fruits"
items={['Select a fruit', 'Banana', 'Apple', 'Orange']}
/>
With React 16.8. We can do this with hooks like the following example
Codesandbox link
import React, { useState } from "react";
import "./styles.css";
export default function App() {
const options = [
"Monty Python and the Holy Grail",
"Monty Python's Life of Brian",
"Monty Python's The Meaning of Life"
];
const filmsByTati = [
{
id: 1,
title: "Jour de fête",
releasedYear: 1949
},
{
id: 2,
title: "Play time",
releasedYear: 1967
},
{
id: 3,
releasedYear: 1958,
title: "Mon Oncle"
}
];
const [selectedOption, setSelectedOption] = useState(options[0]);
const [selectedTatiFilm, setSelectedTatiFilm] = useState(filmsByTati[0]);
return (
<div className="App">
<h1>Select Example</h1>
<select
value={selectedOption}
onChange={(e) => setSelectedOption(e.target.value)}
>
{options.map((option) => (
<option key={option} value={option}>
{option}
</option>
))}
</select>
<span>Selected option: {selectedOption}</span>
<select
value={selectedTatiFilm}
onChange={(e) =>
setSelectedTatiFilm(
filmsByTati.find(film => (film.id == e.target.value))
)
}
>
{filmsByTati.map((film) => (
<option key={film.id} value={film.id}>
{film.title}
</option>
))}
</select>
<span>Selected option: {selectedTatiFilm.title}</span>
</div>
);
}
Simply add as first option of your select tag:
<option disabled hidden value=''></option>
This will become default and when you'll select a valid option will be setted on your state
***Html:***
<div id="divContainer"></div>
var colors = [{ Name: 'Red' }, { Name: 'Green' }, { Name: 'Blue' }];
var selectedColor = 'Green';
ReactDOM.render(<Container></Container>, document.getElementById("divContainer"));
var Container = React.createClass({
render: function () {
return (
<div>
<DropDown data={colors} Selected={selectedColor}></DropDown>
</div>);
}
});
***Option 1:***
var DropDown = React.createClass(
{
render: function () {
var items = this.props.data;
return (
<select value={this.props.Selected}>
{
items.map(function (item) {
return <option value={item.Name }>{item.Name}</option>;
})
}
</select>);
}
});
***Option 2:***
var DropDown = React.createClass(
{
render: function () {
var items = this.props.data;
return (
<select>
{
items.map(function (item) {
return <option value={item.Name} selected={selectedItem == item.Name}>{item.Name}</option>;
})
}
</select>);
}
});
***Option 3:***
var DropDown = React.createClass(
{
render: function () {
var items = this.props.data;
return (
<select>
{
items.map(function (item) {
if (selectedItem == item.Name)
return <option value={item.Name } selected>{item.Name}</option>;
else
return <option value={item.Name }>{item.Name}</option>;
})
}
</select>);
}
});
Use defaultValue to preselect the values for Select.
<Select defaultValue={[{ value: category.published, label: 'Publish' }]} options={statusOptions} onChange={handleStatusChange} />
if you store objects in a state.
class Studentinformation extends Component
{
constructor(props)
{
super(props);
this.handlechange=this.handlechange.bind(this);
this.handleSubmit=this.handleSubmit.bind(this);
this.state={Studentinfo:{
Name:'',
Skill:'Java',
Address:''
}};
}
handlechange(event)
{
const name=event.target.name;
const value=event.target.value;
this.setState({ Studentinfo:
{
...this.state.Studentinfo,
[name]:[value]
}});
}
handleSubmit(event)
{
event.preventDefault();
}
render(){
return (
<div>
<form onSubmit={this.handleSubmit}>
<label>Name: <input type="text" name="Name" value={this.state.Studentinfo.Name} onChange={this.handlechange}></input></label>
<br/>
<label>Skills:
<select value={this.state.Studentinfo.Skill} name="Skill" onChange={this.handlechange}>
<option value="C++" >C++</option>
<option value="C#">C#</option>
<option value="Java">Java</option>
</select>
</label>
<br/>
<textarea value={this.state.Studentinfo.Address} onChange={this.handlechange}/>
<br/>
<input type="submit" value="Submit"></input>
</form>
</div>
);
}
}
I've had a problem with <select> tags not updating to the correct <option> when the state changes. My problem seemed to be that if you render twice in quick succession, the first time with no pre-selected <option> but the second time with one, then the <select> tag doesn't update on the second render, but stays on the default first .
I found a solution to this using refs. You need to get a reference to your <select> tag node (which might be nested in some component), and then manually update the value property on it, in the componentDidUpdate hook.
componentDidUpdate(){
let selectNode = React.findDOMNode(this.refs.selectingComponent.refs.selectTag);
selectNode.value = this.state.someValue;
}
Posting a similar answer for MULTISELECT / optgroups:
render() {
return(
<div>
<select defaultValue="1" onChange={(e) => this.props.changeHandler(e.target.value) }>
<option disabled="disabled" value="1" hidden="hidden">-- Select --</option>
<optgroup label="Group 1">
{options1}
</optgroup>
<optgroup label="Group 2">
{options2}
</optgroup>
</select>
</div>
)
}
I have a simple solution is following the HTML basic.
<input
type="select"
defaultValue=""
>
<option value="" disabled className="text-hide">Please select</option>
<option>value1</option>
<option>value1</option>
</input>
.text-hide is a bootstrap's class, if you not using bootstrap, here you are:
.text-hide {
font: 0/0 a;
color: transparent;
text-shadow: none;
background-color: transparent;
border: 0;
}
if you use Stateless then
const IndexPage =({states, selectedState}) => {
return(
<select id="states" defaultValue={selectedState} name="state">
{states.map(state=> (
<option value={state.id} key={state.id}>{state.name}</option>
))
}
</select>
)
}
I got around a similar issue by setting defaultProps:
ComponentName.defaultProps = {
propName: ''
}
<select value="this.props.propName" ...
So now I avoid errors on compilation if my prop does not exist until mounting.
I have a MongoDB database hosted in MongoDB Atlas, I am using MongoDB Atlas RealM as well to create GraphQL schemas.
I am consuming the GraphQL API in react js application created using Next JS.
I am also using useSWR hooks to fetch the data. With useSWR I don't have any issues fetching the data but when it comes to running the mutation queries using useSWR I am unable to get it done.
There is no proper documentation on how to do it.
Here is my code
//#ts-nocheck
import React, { useContext, useEffect, useState } from "react";
import { Drawer, Button, Form, Input, Select, Cascader } from "antd";
import { TRANSACTION_TYPES } from "queries/transactionTypes";
import { LIST_CATEGORIES } from "queries/categories";
import { FINANCIAL_ACCOUNTS } from "queries/financialAccounts";
import { PAYMENT_MODES } from "queries/paymentModes";
import { INSERT_TRANSACTION } from "queries/transaction";
import useSWR from "swr";
import { AuthContext } from "context/AuthContext";
const AddTransaction = () => {
const userId = useContext(AuthContext);
const { Option } = Select;
const [visible, setVisible] = useState(true);
const [txnType, setTxnType] = useState();
const { data: txnTypeData } = useSWR(TRANSACTION_TYPES);
const { data: categories } = useSWR(LIST_CATEGORIES);
const { data: accounts } = useSWR([FINANCIAL_ACCOUNTS, { user_id: userId }]);
const { data: modes } = useSWR(PAYMENT_MODES);
const { data: transaction, mutate } = useSWR(INSERT_TRANSACTION);
if (txnTypeData && txnTypeData.error) {
return <p>An error occurred: ${txnTypeData.error}</p>;
}
const txnTypes = txnTypeData ? txnTypeData.data.transaction_types : null;
console.log("transaction", transaction);
const options = categories
? categories.data.categories.map((cat) => {
let children = [];
cat.subcategories.forEach((subcat) =>
children.push({
value: subcat,
label: subcat,
})
);
return {
value: cat.name,
label: cat.name,
children,
};
})
: null;
const showDrawer = () => {
setVisible(true);
};
const onClose = () => {
setVisible(false);
};
const handleTxnType = (value) => {
setTxnType(value);
};
const onFinish = (values) => {
const txnData = {};
txnData.date = new Date();
txnData.user_id = userId;
txnData.category = values.category[0];
txnData.subcategory = values.category[1];
txnData.type = values.txntype;
txnData.amount = values.amount;
txnData.description = values.description;
txnData.mode = values.mode;
txnData.account = {
account_name: "ICICI bank",
bank_name: "ICICI bank",
type: "savings",
};
console.log("txnData", txnData);
mutate([INSERT_TRANSACTION, { data: txnData }]);
};
return (
<>
<Button type="primary" onClick={showDrawer}>
Open
</Button>
<Drawer
title="Add Transaction"
placement="right"
onClose={onClose}
visible={visible}
>
<Form
layout={"vertical"}
initialValues={{ remember: true }}
onFinish={onFinish}
autoComplete="off"
>
<Form.Item label="Txn Type" name="txntype">
<Select onChange={handleTxnType}>
{txnTypes &&
txnTypes.map((type) => (
<Option key={type._id} value={type.type}>
{type.type}
</Option>
))}
</Select>
</Form.Item>
<Form.Item label="Cateogry / Subcategory" name="category">
<Cascader options={options} placeholder="Please select" />
</Form.Item>
<Form.Item label="Description" name="description">
<Input placeholder="Proper description of the expense" />
</Form.Item>
<Form.Item label="Amount(₹)" name="amount">
<Input placeholder="Amount" />
</Form.Item>
{txnType !== "self transfer" && (
<Form.Item label="Account" name="account">
<Select>
{accounts &&
accounts.data.financial_accounts.map((acc) => (
<Option key={acc._id}>{acc.name}</Option>
))}
</Select>
</Form.Item>
)}
{txnType === "self transfer" && (
<>
<Form.Item label="From Account" name="from_account">
<Select>
{accounts &&
accounts.data.financial_accounts.map((acc) => (
<Option key={acc._id}>{acc.name}</Option>
))}
</Select>
</Form.Item>
<Form.Item label="To Account" name="to_account">
<Select>
{accounts &&
accounts.data.financial_accounts.map((acc) => (
<Option key={acc._id}>{acc.name}</Option>
))}
</Select>
</Form.Item>
</>
)}
<Form.Item label="Mode" name="mode">
<Select defaultValue="gpay">
{modes &&
modes.data.payment_modes.map((mode) => (
<Option key={mode._id} value={mode.name}>
{mode.name}
</Option>
))}
</Select>
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</Form>
</Drawer>
</>
);
};
export default AddTransaction;
The problem is with this query
const { data: transaction, mutate } = useSWR(INSERT_TRANSACTION);
Here is the mutation query
export const INSERT_TRANSACTION = `
mutation INSERT_TRANSACTION($data: TransactionInsertInput!) {
insertOneTransaction(data: $data) {
_id
}
}
`;
I am calling the mutate function in the onFinish() like this
mutate([INSERT_TRANSACTION, { data: txnData }]);
But, I am getting an error message
message: "Variable \"$data\" of required type \"TransactionInsertInput!\" was not provided."
Not sure, why I am getting this error, as I have already been passing the $data to the query through mutate.
Someone, please shed some light on this, what I am doing wrong here?
I'm trying to submit a form that sends a http request onSubmit, but I'm getting undefined when setting the state on the values. I'm not sure why the values are not being passed upon click and being set with the set...() function.
Below is the code of that component. Upon first submit action I get an error because the "surveyUserAnswers" are undefined, but in the next submissions it works. Not sure why? Could someone advise.
I'm very new to typescript and react hooks, so excuse my code! thanks
import React, { useRef, useState } from "react";
import Loader from "../UI/loader/loader";
import axios from "axios";
import "./surveybox.css";
interface surveryAnswer {
id: number;
answers: string[];
}
const SurveyBox: React.FC = () => {
const [surveyUserAnswers, setSurveyUserAnswers] = useState<surveryAnswer>();
const [loading, setLoading] = useState(false);
const programmingQRef = useRef<HTMLSelectElement>(null);
const skillsQRef = useRef<HTMLSelectElement>(null);
const stateManagementQRef = useRef<HTMLSelectElement>(null);
const programmerTypeQRef = useRef<HTMLSelectElement>(null);
const onSubmitSurvey = (e: React.FormEvent): void => {
e.preventDefault();
setLoading((prevLoading) => !prevLoading);
setSurveyUserAnswers({
id: Math.random(),
answers: [
programmerTypeQRef.current!.value,
skillsQRef.current!.value,
stateManagementQRef.current!.value,
programmerTypeQRef.current!.value,
],
});
axios
.post(`${DB_URL}/users-answers.json`, surveyUserAnswers)
.then((res) => {
setLoading((prevLoading) => !prevLoading);
})
.catch((error) => {
console.log(error);
setLoading((prevLoading) => !prevLoading);
});
};
return (
<div className="surveybox-container">
{loading ? (
<div className={"loader-holder"}>
<Loader />
</div>
) : (
<React.Fragment>
<h2>Quick survey!</h2>
<form action="submit" onSubmit={onSubmitSurvey}>
<label>favorite programming framework?</label>
<select ref={programmingQRef} name="programming">
<option value="React">React</option>
<option value="Vue">Vue</option>
<option value="Angular">Angular</option>
<option value="None of the above">None of the above</option>
</select>
<br></br>
<label>what a junior developer should have?</label>
<select ref={skillsQRef} name="skills">
<option value="Eagerness to lear">Eagerness to learn</option>
<option value="CS Degree">CS Degree</option>
<option value="Commercial experience">
Commercial experience
</option>
<option value="Portfolio">Portfolio</option>
</select>
<br></br>
<label>Redux or Context Api?</label>
<select ref={stateManagementQRef} name="state-management">
<option value="Redux">Redux</option>
<option value="Context Api">Context Api</option>
</select>
<br></br>
<label>Backend, Frontend, Mobile?</label>
<select ref={programmerTypeQRef} name="profession">
<option value="Back-end">back-end</option>
<option value="Front-end">front-end</option>
<option value="mobile">mobile</option>
</select>
<br></br>
<button type="submit">submit</button>
</form>
</React.Fragment>
)}
</div>
);
};
export default SurveyBox;
Setting the state is an async action, and the updated state would only be available at the next render.
In your case, the default state is undefined, and this is what you send at the 1st submit. The state is now updated, and when you submit again, you send the previous answer, and so on...
To solve this, prepare a const (newAnswer), and set it to the state, and use it in the api call.
Note: in your case, you're not using the surveyUserAnswers at all, so you can remove this state entirely.
const onSubmitSurvey = (e: React.FormEvent): void => {
e.preventDefault();
setLoading((prevLoading) => !prevLoading);
const newAnswer = {
id: Math.random(),
answers: [
programmerTypeQRef.current!.value,
skillsQRef.current!.value,
stateManagementQRef.current!.value,
programmerTypeQRef.current!.value,
],
}
setSurveyUserAnswers(newAnswer);
axios
.post(`${DB_URL}/users-answers.json`, newAnswer)
.then((res) => {
setLoading((prevLoading) => !prevLoading);
})
.catch((error) => {
console.log(error);
setLoading((prevLoading) => !prevLoading);
});
};
I found this tutorial on how to create a react quizz app on youtube link to tutorial
I am trying to set the title based on the current Select Option Value when submitting the form.
Currently I managed to change the title only when a different option is selected.
import React, { useState, useEffect, useRef } from "react";
import "./App.css";
import axios from "axios";
import FlashcardList from "./components/FlashcardList";
function App() {
const [flashcards, setFlashcards] = useState([]);
const [categories, setCategories] = useState([]);
const [title, setTitle] = useState("General Knowledge");
const categoryEl = useRef();
const amountEl = useRef();
useEffect(() => {
axios.get("https://opentdb.com/api_category.php").then((res) => {
setCategories(res.data.trivia_categories);
});
}, []);
function decodeString(str) {
const textArea = document.createElement("textarea");
textArea.innerHTML = str;
return textArea.value;
}
function handleSubmit(e) {
e.preventDefault();
axios
.get("https://opentdb.com/api.php", {
params: {
amount: amountEl.current.value,
category: categoryEl.current.value,
},
})
.then((res) => {
setFlashcards(
res.data.results.map((questionItem, index) => {
const answer = decodeString(questionItem.correct_answer);
const options = [...questionItem.incorrect_answers, answer];
return {
id: `${index} - ${Date.now()}`,
question: decodeString(questionItem.question),
answer: answer,
options: options.sort(() => Math.random() - 0.5),
};
})
);
});
}
function getTitle(e) {
setTitle(e.target.options[e.target.selectedIndex].text);
}
return (
<>
<form className="header" onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="category">Category</label>
<select id="category" ref={categoryEl} onChange={getTitle}>
{categories.map((category) => {
return (
<option value={category.id} key={category.id}>
{category.name}
</option>
);
})}
</select>
</div>
<div className="form-group">
<label htmlFor="amount">Number Of Questions</label>
<input
type="number"
id="amount"
min="1"
step="1"
defaultValue={10}
ref={amountEl}
/>
</div>
<div className="form-group">
<button className="btn">Generate</button>
</div>
</form>
<div className="container">
<h1 className="title">{title}</h1>
<FlashcardList flashcards={flashcards} />
</div>
</>
);
}
export default App;
Code
Live demo
You can set the category as soon the categories are fetched. Can just use the zeroth element to set the title.
useEffect(() => { axios.get("https://opentdb.com/api_category.php").then((res) => {
setCategories(res.data.trivia_categories);
setTitle(res.data.trivia_categories[0]);
});
}, []);
When I make a selection from the dropdown I saved the selected value to type then when I click the button I add an object to drums, I map over thee drums and based on the type I want to render the component with the same name.
Sandbox here
import React, { useState } from "react";
import uuid from "react-uuid";
import "./styles.css";
const Snare = () => {
return <div>Snare</div>;
};
const Gong = () => {
return <div>Gong</div>;
};
export default function App() {
const [drums, setDrums] = useState([]);
const [type, setType] = useState();
return (
<div className="App">
{drums.map((Drum, index) => (
<Drum.type /> // Why cant I use `.type`?
))}
<label>
Drum type to add:
<select onChange={e => setType(e.target.value)} value={type}>
<option value="">Select...</option>
<option value="Snare">Snare</option>
<option value="Gong">Gong</option>
</select>
<button
onClick={() => {
setDrums([...drums,
{
id: uuid(),
type
}
]);
}}
>
Add drum
</button>
</label>
</div>
);
}
In your case Drum.type is not a component but a string, you need to maintain a map of the string to component and then render it
const map = {
Snare: Snare,
Gong: Gong
};
export default function App() {
const [drums, setDrums] = useState([]);
const [type, setType] = useState();
return (
<div className="App">
{drums.map((Drum, index) => {
const Component = map[Drum.type];
return <Component key={index}/>;
})}
<label>
Drum type to add:
<select onChange={e => setType(e.target.value)} value={type}>
<option value="">Select...</option>
<option value="Snare">Snare</option>
<option value="Gong">Gong</option>
</select>
<button
onClick={() => {
setDrums([
...drums,
{
id: uuid(),
type
}
]);
}}
>
Add drum
</button>
</label>
</div>
);
}
Working demo
That's because the type is a string.
You could create a mapping to solve this and use React.createElement().
Something like:
const mapping = {
'Snare': Snare,
'Gong': Gong
}
{ drums.map(({ type }, index) => (
React.createElement(mapping[type], { key: index })
))
}