The bootstrap switches not seems to be working. Even the documentation version not workng
<Form>
<Form.Check
type="switch"
id="custom-switch"
label="Check this switch"
/>
<Form.Check
disabled
type="switch"
label="disabled switch"
id="disabled-custom-switch"
/>
</Form>
Simple FormCheck is working for me:
<FormCheck
id="switchEnabled"
type="switch"
checked={this.state.settings.enabled}
onChange={this.toggleEnabled}
label="Enable"
/>
The key point was to provide id. Another important thing (to load the initial value) was to use checked property.
Unfortunately documentation for the switch isn't the greatest. Nevertheless, the following should help with setting up the switch for your use.
const [isSwitchOn, setIsSwitchOn] = useState(false);
const onSwitchAction = () => {
setIsSwitchOn(!isSwitchOn);
};
...
<Form>
<Form.Switch
onChange={onSwitchAction}
id="custom-switch"
label="anything you want to put here"
checked={isSwitchOn}
disabled // apply if you want the switch disabled
/>
</Form>
...
I found an approach.
import React from "react";
import ReactDOM from "react-dom";
import { Container, Form, FormCheck, Button } from "react-bootstrap";
import "./styles.css";
import "bootstrap/dist/css/bootstrap.min.css";
function App() {
const [swt, setSwt] = React.useState(true);
const [swt2, setSwt2] = React.useState(true);
return (
<Container className="App">
Aprroch 1
<FormCheck custom type="switch">
<FormCheck.Input isInvalid checked={swt} />
<FormCheck.Label onClick={() => setSwt(!swt)}>
{`Value is ${swt}`}
</FormCheck.Label>
</FormCheck>
Approch 2
<Form.Check custom type="switch">
<Form.Check.Input isInvalid checked={swt2} />
<Form.Check.Label onClick={() => setSwt2(!swt2)}>
{`Value is ${swt2}`}
</Form.Check.Label>
</Form.Check>
</Container>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
codeSandbox
If you add the custom property it will show the switch button, but I'm still not able to toggle the switch...
<Form>
<Form.Check
custom
type="switch"
id="custom-switch"
label="Check this switch"
/>
</Form>
I had a similar issue and adding custom as suggested in another answer showed the switch correctly but similarly the toggle would now work.
I noticed that I was pointing at an older version of react-bootstrap so changed this to point to the current version which at the time is v1.0.0-beta.16 and this allowed the toggle to work and custom to be removed.
So best to make sure you are pointing at the latest version of react-bootstrap if you're having problems like this: React Bootstrap
I used classes like simple bootstrap
<div className="form-check form-switch">
<input className="form-check-input" type="checkbox" id="flexSwitchCheckDefault"/>
<label className="form-check-label" for="flexSwitchCheckDefault">
switch checkbox input
</label>
</div>
<FormCheck
id="switchEnabled1"
type="switch"
checked={this.state.settings.enabled}
onChange={this.toggleEnabled}
label="Enable"
/>
Changing the id of the switch from switchEnabled to switchEnabled1 seems to be working. You have to have different id for the switch if you are using it at multiple places.
I think we need to use useState like this
<Form.Check
type="switch"
id="custom-switch"
label="Email"
checked={emailChecked}
onChange = {() => setEmailChecked(!emailChecked)}
style={{ marginLeft: '20px' }}
/>
Related
I want to make the button with the FaPlus icon to render a form OnClick (or OnPress, i've seen that's an option too but i don't know if it makes any difference in comparison) but React says "añadirCurso" (the arrow function) is not defined, any ideas? (i was using part of the code of another question similar to this, but maybe it doesn't work because that code was in a class that extended Component)
Here's the code
import React from "react";
import Button from 'react-bootstrap/Button';
import {aulas} from '../props/aulas';
import Container from 'react-bootstrap/Container';
import AppBar from '#mui/material/AppBar';
import Toolbar from '#mui/material/Toolbar';
import {FaPlus} from 'react-icons/fa';
import { Route, useNavigate } from "react-router-dom";
export default function AdministrarCurso_Preceptor(){
const navigate= useNavigate();
const state= {añadirCurso: false};
añadirCurso= () =>{
return (
<div>
<form method="GET" action="#">
<legend>Añadir Curso</legend>
<label htmlFor="usuario">Nombre de Usuario</label> <br/>
<input required type="text" name="usuario" defaultValue="" /> <br/>
</form>
</div>
)
}
return(
<Container>
<AppBar style={{background: 'transparent', boxShadow: 'none'}}>
<Toolbar>
<Button className="btn btn-success" sx={{flexGrow: 1}}>
<FaPlus/>
</Button>
<Button onClick={()=> navigate('/LoginForm')}>Cerrar Sesión</Button>
</Toolbar>
</AppBar>
<div className="row">
{/* Acá hay un map que muestra todo el contenido del prop aulas
y le asigna un botón dentro de filas y columnas hechas
mientras se toma el contenido del array */}
{aulas.map((aula, i) => (
<div key={i} className="col-md-4" style={{paddingBottom: '10px', paddingTop: '5px'}}>
<Button className={(aula.estado==='sucio'? 'btn btn-danger': 'btn btn-success')}>{aula.año}{aula.division}</Button>
</div>
))}
</div>
</Container>
)
}
And for the "saving it on props" part, as i've said in a previous question i have a props file with classrooms (aulas) and i want the form data to save in that file on Submit, so that when you click on the submit button it saves the data there, and since it's in that file, it should render a new button, is it possible?
There are a couple of reasons regarding why your code is not working.
First of all, as you mentioned the code belonged to a class component and it seems like you simply pasted that in your functional component.
You need to use const before the arrow function's name.
Rather than returning JSX, I'd highly (like really highly) recommend you to use a state like
const [isFormVisible, setIsFormVisible] = useState(false);
and then on click of the button, you just set the state to true. and use the variable for conditional rendering like this....
{isFormVisible && (<theJSXGoesHere />)}
In a function, I have a button that displays a component on click. How do I hide this component when clicking on that button again (which would work like a toggle)?
<Link to="/">
<div className="navigation">
<button
className="about-button"
>
About
</button>
</div>
</Link>
<Switch>
<Route path="/" exact>
<HomePage />
</Route>
</Switch>
Your doing this a bit different then how you normally would approach this. Let me write a quick component from scratch to show you the idea...
import React, { useState } from 'react'
export default const ExampleComponent = () => {
const [showElem, setShowElem] = useState(true)
return (
<div>
{ showElem && <h1>Hello</h1> }
<Button onClick={() => {
setShowElem(!showElem)
}} />
</div>
)
}
...You'll have to excuse the formatting I typed this up right here.
I understand now that toggling is not recommended with React Routing.
I have been trying to use material-ui and iterate over it inside an array ( for creating ratings for some items like in e-commerce sites). The code isn't working. On my localhost server, it's not showing any stars at all. Before I made it dynamic, it was working all fine, then I added props to my functional component as per to make it dynamic. Everything else is working just fine except that it's not accepting my matrial-ui icon inside the array for me to iterate over. Moreover, the import statement says "it's value is never read although it's imported"
My code: Product.js:
import React from "react";
import "./Product.css";
import StarRateIcon from "#material-ui/icons/StarRate";
function Product({ id, title, image, price, rating }) {
return (
<div className="product">
<div className="product_info">
<p>{title}</p>
<p className="product_price">
<small>$</small>
<strong>{price}</strong>
</p>
<div className="product_rating">
{Array(rating)
.fill()
.map((_, i) => (
<p StarRateIcon className="star" />
))}
</div>
</div>
<img src={image} alt="" />
<button>Add to Basket</button>
</div>
);
}
export default Product;
My home.js file :
import React from "react";
import "./Home.css";
import Product from "./Product";
function Home() {
return (
<div classname="home">
<div className="home_container">
<img
className="home_image"
src="https://m.media-amazon.com/images/G/01/digital/video/sonata/US3P_JOKER_IMAGE_ID/be07783e-2738-4aaf-b90c-d0ec474d15ae._UR3000,600_SX1500_FMwebp_.jpg"
/>
<div className="home_row">
<Product
id="890778"
title="Description"
price={99.99}
image="https://m.media-amazon.com/images/I/71BGLa7IFtL._AC_UY218_.jpg"
rating={5}
/>
<Product />
</div>
</div>
</div>
);
}
export default Home;
Help Somebody! I can use emoji snippets but I really want this to work. I have imported StarRateIcon and used it. It isn't working.
Looks like you accidentally put a 'p' in front of your icon component name. You have <p StarRateIcon className="star" /> when it should be <StarRateIcon className="star" />
You're rendering a p tag with no content with an invalid attribute, StarRateIcon. It's the reason you're not seeing anything rendered. If you inspect the HTML, you'll most likely see the p tags. You may also see errors in the console about invalid attributes. Your code should look something like this:
Array(rating).fill().map(() => <StarRateIcon className="star" />)
I have a reusable input/checkbox component that takes in a label prop:
<Checkbox
label="I have read and understood the Terms of Service and consent to the Privacy Policy"
/>
and my checkbox's render:
<label>
<input
type='checkbox'
disabled={this.props.disabled}
onChange={this.handleChange}
checked={this.props.value}
placeholder={this.props.placeholder}
/>
{this.label}
</label>
however I want the label to accept something like
<Checkbox
label="I have read and understood the Terms of Service and consent to the Privacy Policy"
/>
and have the words Terms of Service and Privacy Policy as links. However this doesn't work.
Do I have to use something like dangerouslySetInnerHtml to achieve something like this? From wha tI understand using innerHTML is a risk, is it not?
What would be the best way to modify my component to be able to add links like this?
You can pass in JSX for the label prop instead of a string, for example:
<Checkbox
label={
<>
I have read and understood the Terms of Service{" "}
and consent to the Privacy Policy
</>
}
/>;
Here is a full example:
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
const Checkbox = props => {
return (
<label>
<input
type="checkbox"
disabled={props.disabled}
onChange={props.handleChange}
checked={props.value}
placeholder={props.placeholder}
/>
{props.label}
</label>
);
};
function App() {
return (
<div className="App">
<Checkbox
label={
<>
I have read and understood the{" "}
Terms of Service and consent to the{" "}
Privacy Policy
</>
}
/>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
You can view the full interactive example here
In the below code, why does a call to the classes object work? It seems like the call should be to the styles object defined as a const up top.
For example, in this demo:
className={classes.button}
works as written. But it seems like it should be
className={styles.button}
Is there any actual classes object defined anywhere? If so, where is it defined? The markup implies a this.props.classes object. But there are no props passed to <Demo /> when called in index.js.
What's going on here?
https://codesandbox.io/s/qxv466wlq
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '#material-ui/core/styles';
import Button from '#material-ui/core/Button';
const styles = theme => ({
button: {
margin: theme.spacing.unit,
},
input: {
display: 'none',
},
});
function OutlinedButtons(props) {
const { classes } = props;
return (
<div>
<Button variant="outlined" className={classes.button}>
Default
</Button>
<Button variant="outlined" color="primary" className={classes.button}>
Primary
</Button>
<Button variant="outlined" color="secondary" className={classes.button}>
Secondary
</Button>
<Button variant="outlined" disabled className={classes.button}>
Disabled
</Button>
<Button variant="outlined" href="#outlined-buttons" className={classes.button}>
Link
</Button>
<input
accept="image/*"
className={classes.input}
id="outlined-button-file"
multiple
type="file"
/>
<label htmlFor="outlined-button-file">
<Button variant="outlined" component="span" className={classes.button}>
Upload
</Button>
</label>
</div>
);
}
OutlinedButtons.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(OutlinedButtons);
If you look at this line:
export default withStyles(styles)(OutlinedButtons);
the answer to your question is provided I believe. Material UI has a function withStyles that takes a styles object, and then returns another function that takes a component to return a new component. This is a Higher Order Component, and can be read about on the React docs.
If you look at the linked code of withStyles, you can see the following line where it renders the passed in component:
return <Component {...more} classes={this.getClasses()} ref={innerRef} />;
And is providing the classes prop, making it available to any component exported with withStyles.