How to conditionally show element in react JSX? - javascript

I am creating a UI dynamically using JSON data which renders input or textarea elements conditionally.
Sample JSON Data
[
{
type: "input",
val: "input text",
name: "Input Field",
editable: false
},
{
type: "text",
val: "text area text",
name: "Text area field",
editable: true
},
{
type: "text",
val: "text area text",
name: "Text area field",
editable: true
}
];
I have two values for property type one is input other is text, So if type property has value "input" then I am creating an input element otherwise textarea element.
I too have extra properties. One of them is editable, if it is set to true then user can click on edit button which which show Send button later on.
Issues
When I am clicking on edit both input field getting editable and both Edit is changing to Send
I tried using index and matching with index, but that also did not work.
My code
{data.map((li, index) => (
<div className="col-12 col-sm-12 col-md-6 col-lg-6 col-xl-6">
{li.type === "input" && (
<div className="divCont">
{li.editable && disabled && (
<span onClick={editComp}>Edit</span>
)}
<input
type="text"
className="form-control"
disabled={disabled}
defaultValue={li.val}
/>
</div>
)}
{li.type === "text" && (
<div className="divCont">
{li.editable && disabled && (
<span onClick={(e) => editComp(index)}>Edit</span>
)}
{disabled === false && ind === index && (
<span onClick={editComp}>Send</span>
)}
<input
type="text"
className="form-control"
disabled={disabled}
defaultValue={li.val}
/>
</div>
)}
</div>
))}
Code sandbox
Edit / Update
What I am trying to do
When the object have property editable:true it shows the edit button
just above the input or textarea element.
Then when I click on edit I want to make sure that particular input or textarea element is enabled so that user can type. Edit button should be changed to Send button to send data.

You are using the same flag 'disabled' to control the state of all your components. Therefore, when you click on send you change it to false for every field and that renders them all editable. The easiest fix would be to use a different flag for each field, but that may not scale well if you need it to.

Okay, I understand that you probably new to React and maybe even programming. Learning is good. Here some updated version of your code which does what you wanted, at least the way I have understood. Note though, I have no idea what you trying to build here, but hopefully it will give you some new start:
import React, { useState } from "react";
import "./styles.css";
import "bootstrap/dist/css/bootstrap.min.css";
function EditableArea({ val, ...rest }) {
const [disabled, setDisabled] = useState(true);
const [value, setValue] = useState(rest.value);
const handleSend = () => {
// ... send it somewhere maybe?..
console.log(value);
setDisabled(true);
};
return (
<div className="divCont">
{disabled ? (
<span onClick={() => setDisabled(false)}>Edit</span>
) : (
<span onClick={handleSend}>Send</span>
)}
<textarea
type="text"
className="form-control"
disabled={disabled}
placeholder={rest.placeholder}
onChange={(e) => setValue(e.target.value)}
value={value}
></textarea>
</div>
);
}
function Editable({ ...rest }) {
const [disabled, setDisabled] = useState(true);
const [value, setValue] = useState(rest.value || "");
const handleSend = () => {
// ... send it somewhere maybe?..
console.log(value);
setDisabled(true);
};
return (
<div className="divCont">
{disabled ? (
<span onClick={() => setDisabled(false)}>Edit</span>
) : (
<span onClick={handleSend}>Send</span>
)}
<input
type="text"
className="form-control"
disabled={disabled}
placeholder={rest.placeholder}
value={value}
onChange={(e) => setValue(e.target.value)}
/>
</div>
);
}
let data = [
{
type: "input",
val: "input text",
name: "Input Field",
editable: false
},
{
type: "text",
placeholder: "text area text",
name: "Text area field",
editable: true,
value: ""
},
{
type: "text",
placeholder: "text area text",
name: "Text area field",
editable: true,
value: ""
}
];
function redrerInput({ type, editable, ...rest }) {
switch (type) {
case "text":
return <EditableArea {...rest} />;
case "input":
return <Editable {...rest} />;
default:
return null;
}
}
export default function App() {
return (
<div className="App">
<div className="row">
{data.map((item, i) => (
<div key={i} className="col-12 col-sm-12 col-md-6 col-lg-6 col-xl-6">
{redrerInput(item)}
</div>
))}
</div>
</div>
);
}
Here is CodeSandbox fork
But I would strongly recommend to read documentation about React first.

Related

one onChange input, wrongly modifies other three tags content

I have the next state:
const [social_networks, setSocial_networks] = useState([
{
social_account_type: "personal",
social_network: "linkedin",
handle: "",
content: ""
},
{
social_account_type: "company",
social_network: "twitter",
handle: "",
content: ""
},
{
social_account_type: "personal",
social_network: "webpage",
handle: "",
content: ""
}
])
In the parent component I declare the function:
const handleInputChange = (e, index) => {
const { name, value } = e.target;
const list = [...social_networks];
list[index][name] = value;
setSocial_networks(list);
};
Set this to the children in the next code:
social_networks.map((social_network, idx) => {
if (social_network.social_account_type == "personal") return <div key={idx}><AccountsPill handle={social_network.handle} social={social_network.social_network} content={social_network.handle} index={idx} handleInputChange={handleInputChange} /> </div>
})
And into my child component I have the next code:
<div className="row m-0">
<div className="svg-container col-md-1">
<BrowserIcon color="#868E96" />
</div>
<input type="text" className="col-md-11 set-account-input" placeholder=
{"www."+props.social+".com"} name="handle" id="handle" defaultValue={props.handle}
onChange={e => props.handleInputChange(e, props.index)} />
</div>
<div className="row m-0">
<div className="svg-container col-md-1">
<AtIcon color="#868E96" />
</div>
<input type="text" className="col-md-11 set-account-input" placeholder="MyUsername"
name="content" id="content" defaultValue={props.content} onChange={e =>
props.handleInputChange(e, props.index)} />
</div>
The page show me like that:
after rendering frontpage
When I change the input.Content works fine:
input.name=content change
But, if I change the input.name=handle , change the other input too:
input.name=handle change
I tried to make two differents handleChange functions, change the props.name, add the props.id, but does'nt works yet.
You passed wrong content props to your AccountsPill component, it should be
<AccountsPill
handle={social_network.handle}
social={social_network.social_network}
content={social_network.content}
index={idx}
handleInputChange={handleInputChange}
/>
I think your problem is that const list = [...social_networks]; shallow copies the state array, so it's really just an array of the original state objects. Try instead:
const handleInputChange = (e, index) => {
const { name, value } = e.target;
const list = social_networks.map((social, i)=>{
if(index === i){
return {...social, [name]: value}
}
return {...social}
})
setSocial_networks(list);
};

How change the format of checkbox in react final form

I implemented the form through react final form
const products= [
{ label: "T Shirt", value: "tshirt" },
{ label: "White Mug", value: "cup" },
{ label: "G-Shock", value: "watch" },
{ label: "Hawaiian Shorts", value: "shorts" },
];
<>
<Form
onSubmit={onSubmit}
render={({ handleSubmit, pristine, invalid, values }) => (
<form onSubmit={handleSubmit} className="p-5">
{products &&
products.map((product, idx) => (
<div className="custom-control custom-checkbox" key={idx}>
<Field
name="state"
component="input"
type="checkbox"
value={product.value}
/>
<label
className="custom-control-label"
htmlFor={`customCheck1-${product.value}`}
>
{product.label}
</label>
</div>
))}
<button type="submit" disabled={pristine || invalid}>
Submit
</button>
<pre>{JSON.stringify(values, 0, 2)}</pre>
</form>
)}
/>
</>
If I am selecting checkboxes the checked values are showing array of values like [tshirt,cup] but I need to show the array of objects like [ { label: "T Shirt", value: "tshirt" }, { label: "White Mug", value: "cup" }]
I tried so many ways but I have not any luck. Please help me to out of this problem
values will always be the array consisting of the "value" attribute for the Field tag.
If you want the object from the products array,you could do the following
console.log(values.map(val => products.find(p => p.value === val)))
or create an object first via reduce & then use it.
const obj =products.reduce((map,p)=>{
map[value]=p
return map
},{})
console.log(values.map(v => productMap[v]))
add a onchange method to you input. the method must take value of product.
const [selectedProducts, setSelectedProducts] = useState([]);
const handleChange = (value) =>{
const itemToAdd = products.find(product => product.value === value);
const index = selectedProducts.findIndex(item => item.value === value);
if (index === -1){
setSelectedProducts([...selectedProducts, products[index]])
}else {
const data = [...selectedProducts];
data.splice(index, 1);
setSelectedProducts(data);
}
}
some change to jsx
<Field
onChange = {handleChange}
name="state"
component="input"
type="checkbox"
value={product.value}
checked = {selectedProducts.findIndex(item => item.value === value)!== -1}
/>

Render a radio button as already selected on page load - React js

I have this component:
import React from 'react';
const options = [
{ label: "Lifestyle", value: "lifestyle"},
{ label: "Area", value: "area" },
{ label: "Random", value: "random" }
];
const ChannelCategory = props =>
props.visible ? (
<div>
{props.title}
<ul>
{options.map((option) => (
<li key={option.value}>
<label>
{option.label}
<input
className={props.className}
name={props.name} // need to be different
selected={props.selected === option.value} // e.g. lifestyle === lifestyle
onChange={() => props.onChange(option.value)}
type="radio"
/>
</label>
</li>
))}
</ul>
</div>
) : null;
export default ChannelCategory;
I am rendering it on another page here in a .map:
let displayExistingChannels = null;
if (channels !== null){
displayExistingChannels = (
channels.map(channel => {
return (
<Grid key={channel.key} item style={styles.gridItem} justify="space-between">
<ChannelListItem
channel={channel}
isSaving={isSaving}
onDeleteChannelClick={onDeleteChannelClick}
key={channel.key}
onFormControlChange={onFormControlChange}
onUndoChannelClick={onUndoChannelClick}
/>
{channel.category}
<ChannelCategory
visible={true}
onChange={value => setCategoryName(value)}
title="Edit Category"
selected={channel.category}
name={channel.key} // unique for every channel
/>
</Grid>
)
})
)
}
I am using fake data for the map:
const fakeChannelData = setupChannels(
[{id: "2f469", name: "shopping ", readOnly: false, category: "lifestyle"},
{id: "bae96", name: "public", readOnly: true, category: "null"},
{id: "06ea6", name: "swimming ", readOnly: false, category: "sport"},
{id: "7e2bb", name: "comedy shows ", readOnly: false, category: "entertainment"}]);
const [channels, setChannels] = useState(fakeChannelData);
Please can someone tell me why when I add selected={channel.category} in my .map function it does not show the selected category preselected on the FE on page load? Not sure where I have gone wrong? Thanks!
checked is the correct attribute to use for input tag, not selected.
<input
...
checked={props.selected === option.value}
...
/>
ref: https://developer.mozilla.org/fr/docs/Web/HTML/Element/Input/radio

How can I check only one check box at a time instead of all in a list of checkboxes in React

I have a list of chat room channels for people to talk i.e there is a lifestyle channel, shopping channel, pets channel etc.
I am now trying to categorise each channel to make it easier for the user to find what they want. In order to do so, on creation of a chatroom channel I need the user to select which category the channel they are creating best fits into. A bit like YouTube does when you upload a video.
So far I have created a separate component which is a list of checkboxes with the different categories the user can put their channel into:
import React from 'react';
const options = [
{ label: "Lifestyle", value: "lifestyle"},
{ label: "Area", value: "area" },
{ label: "Random", value: "random" },
{ label: "Comedy", value: "comedy" },
{ label: "Entertainment", value: "entertainment" }
];
const ChannelCategory = (props) => {
return (
<div>
{props.title}
<ul>
{options.map((option) => (
<li key={props.key}>
<label>
{option.label}
<input
className={props.className}
name="test"
checked={props.checked}
onChange={() => props.onChange(option.value)}
type="checkbox"
/>
</label>
</li>
))}
</ul>
</div>
)
};
export default ChannelCategory;
I am using the above component on the page below, I would like that when the user selects just ONE of the options only ONE input box is checked, however at the moment when I click ONE input box for instance lifestyle they ALLLL get checked and for every single channel too:( Any ideas why?
const [checked, setCheckBoxChecked] = useState(false);
[...]
const onAddCategory = (value) => {
console.log(value);
if (value === "lifestyle") {
setCheckBoxChecked(checked => !checked);
}
if (value === "area") {
setCheckBoxChecked(checked => !checked);
}
if (value === "random") {
setCheckBoxChecked(checked => !checked);
}
if (value === "comedy") {
setCheckBoxChecked(checked => !checked);
}
};
[...]
const options = [
{ label: "Lifestyle", value: "lifestyle"},
{ label: "Area", value: "area" },
{ label: "Random", value: "random" },
{ label: "Comedy", value: "comedy" },
{ label: "Entertainment", value: "entertainment" }
];
return (
<form noValidate autoComplete='off' onSubmit={onSubmit}>
<Card style={styles.card}>
<CardContent>
<Box padding={3}>
<FormLegend title={`${formTitle} (${channels.length})`} description={formDescription} />
<Box marginTop={3} width='50%'>
<Grid container direction='column' justify='flex-start' alignItems='stretch' spacing={1}>
{channels.map(channel => {
return (
<Grid key={channel.key} item style={styles.gridItem} justify="space-between">
<ChannelListItem
channel={channel}
isSaving={isSaving}
onDeleteChannelClick={onDeleteChannelClick}
key={channel.Key}
onFormControlChange={onFormControlChange}
onUndoChannelClick={onUndoChannelClick}
/>
<ChannelCategory
key={channel.key}
options={options}
onChange={value => onAddCategory(value)}
title="Add your chatroom to a category so that users can find it easily"
checked={checked}
/>
</Grid>
)
})}
[...]
</Grid>
</Grid>
</Box>
</Box>
</CardContent>
</Card>
</form>
);
Instead of storing true or false inside the checked variable, you should store the value inside of checked. Like this:
const onChangeAttribute = (value) => {
console.log(value);
setCheckBoxChecked(value);
};
And now while rendering the checkbox you should check if checked is equal to the name of that checkbox like this:
<input
className={props.className}
name={option.value}
checked={props.checked === option.value}
onChange={() => props.onChange(option.value)}
type="checkbox"
/>
This should resolve your issue.
Use an array to store all checked boxes and in your ChannelCategory check if the current value exists in the checked array then set checked to true for that checkbox. If you want to select only one category use radio buttons
const {useState, useEffect} = React;
const options = [
{ label: "Lifestyle", value: "lifestyle" },
{ label: "Area", value: "area" },
{ label: "Random", value: "random" },
{ label: "Comedy", value: "comedy" },
{ label: "Entertainment", value: "entertainment" }
];
const ChannelCategory = props => {
return (
<div>
{props.title}
<ul>
{props.options.map(option => (
<li key={props.key}>
<label>
{option.label}
<input
className={props.className}
name={option.value}
checked={props.checked.includes(option.value)}
onChange={e => props.onChange(e.target.checked, option.value)}
type="checkbox"
/>
</label>
</li>
))}
</ul>
</div>
);
};
function App() {
const [checked, setCheckBoxChecked] = useState([]);
const onAddCategory = (isChecked, value) => {
const temp = [...checked];
if (isChecked) {
temp.push(value);
setCheckBoxChecked(temp);
return;
}
setCheckBoxChecked(temp.filter(item => item !== value));
};
return (
<div className="App">
<ChannelCategory
key={"channel.key"}
options={options}
onChange={onAddCategory}
title="Add your chatroom to a category so that users can find it easily"
checked={checked}
/>
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>
Radio buttons example

React checkbox feature with only single selection

I want to figure out whether my code is wrong or a bug. I think there is no problem, but it does not work...
The code I used is:
https://codepen.io/cadenzah/pen/wvwYLgj?editors=0010
class ItemView extends React.Component {
constructor(props) {
super(props)
this.state = {
options: [{
id: 1,
name: "Item 1"
},
{
id: 2,
name: "Item 2"
}],
optionSelected: 2
}
}
toggleCheckbox(e) {
console.log(e.target.id)
if (this.state.optionSelected === e.target.id) {
this.setState({
optionSelected: undefined
})
} else {
this.setState({ optionSelected: e.target.id })
}
}
render() {
return (
<div className="container">
<div className="row">
<ItemList
options={this.state.options}
optionSelected={this.state.optionSelected}
toggleCheckbox={(e) => this.toggleCheckbox(e)} />
</div>
</div>
)
}
}
const ItemList = ({ options, optionSelected, toggleCheckbox }) => {
return (
<div className="col s12">
{
options.map((option, index) => (
<Item
key={index}
option={option}
checked={(optionSelected === (index + 1) ? true : false)}
toggleCheckbox={toggleCheckbox} />
))
}
</div>
)
}
const Item = ({ option, checked, toggleCheckbox }) => {
return (
<div className="card">
<div className="card-content">
<p><label htmlFor={option.id}>
<input
className="filled-in"
type="checkbox"
id={option.id}
onChange={toggleCheckbox}
checked={(checked ? "checked" : "")} />
<span>{option.id}. {option.name}</span>
</label></p>
</div>
</div>
)
}
Code explaination:
React code, with materialize-css used.
It is a simple checkbox feature with multiple items, restricted to select only one item. So, if I check one of them, every item except for what I just selected will be unchecked automatically. If I uncheck what I just checked, every item will stay unchecked.
The core logic is: in <ItemList /> component, there is a conditional props that determines whether each item has to be checked or not. It compares the id, and hand in true or false into its children. That checked props is used in <Item /> component to set the checked attribute of <input>.
Strange thing is, as I set default choice in the initial state, when I just run the application, the check feature works as I expected. But if I click one of them, it does not work.
What is the problem of it?
You can check if the selected option is the checked one like this:
checked={optionSelected === option.id}
And then you simply get it into your input like this:
<input checked={checked} />
Also, make sure to change your state ids into strings (the DOM element id is of type string):
options: [{
id: '1',
name: "Item 1"
},
{
id: '2',
name: "Item 2"
}],
optionSelected: '2'
https://codepen.io/AndrewRed/pen/gOYBVPZ?editors=0010
class ItemView extends React.Component {
constructor(props) {
super(props)
this.state = {
options: [{
id: 1,
name: "Item 1"
},
{
id: 2,
name: "Item 2"
}],
optionSelected: 2
}
}
toggleCheckbox(e) {
this.setState({
optionSelected : e.target.id
})
}
render() {
return (
<div className="container">
<div className="row">
<ItemList
options={this.state.options}
optionSelected={this.state.optionSelected}
toggleCheckbox={(e) => this.toggleCheckbox(e)} />
</div>
</div>
)
}
}
const ItemList = ({ options, optionSelected, toggleCheckbox }) => {
return (
<div className="col s12">
{
options.map((option, index) => (
<Item
key={index}
option={option}
checked={(optionSelected === (index + 1) ? true : false)}
toggleCheckbox={toggleCheckbox}
optionSelected = {optionSelected}
/>
))
}
</div>
)
}
const Item = ({ option, checked, toggleCheckbox,optionSelected }) => {
return (
<div className="card">
<div className="card-content">
<p><label htmlFor={option.id}>
<input
className="filled-in"
type="checkbox"
id={option.id}
onChange={toggleCheckbox}
checked={option.id == optionSelected ? "checked" : ""} />
<span>{option.id}. {option.name}</span>
</label></p>
</div>
</div>
)
}
function tick() {
ReactDOM.render(
<ItemView />,
document.getElementById('root')
);
}
tick()
COPY PASTE AND RUN
e.target.id is a string while index is a number. When you do a === comparison the type is also checked and these are not the same. This results in checked always being false after the initial state (which you set yourself as an int)

Categories