reactstrap | Simple React Bootstrap 5 components | Frontend Framework library
kandi X-RAY | reactstrap Summary
Support
Quality
Security
License
Reuse
Currently covering the most popular Java, JavaScript and Python libraries. See a Sample Here
reactstrap Key Features
reactstrap Examples and Code Snippets
Trending Discussions on reactstrap
Trending Discussions on reactstrap
QUESTION
Code:
import { CustomInput } from 'reactstrap'
...
const changeMediaStatus = (e) => {
console.log(e)
}
...
changeMediaStatus(e)}
/>
On the above code, the function that is assigned at "onChange" prop is not working. And also, CustomInput component with onChange prop is not working.
How can I assign a function to onChange event at reactstrap CustomInput compoenent?
ANSWER
Answered 2021-Jun-15 at 09:08Provide id
for the CustomInput.
changeMediaStatus(e)}
/>
QUESTION
I am learning Redux Thunk now. I tried to use createAsyncThunk
from Redux Toolkit
to deal with user log in and I encountered some problems. I created a demo here ('right@gmail.com' + whatever password => success, other combination => rejection).
I created a modal for users to input their emails and passwords using reactstrap
. Click the Login
button then you will see the form.
Here is my UserSlice.js
file:
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { loginFeedback } from "./feedBack";
export const login = createAsyncThunk(
"user/login",
async (userInfo, { rejectWithValue }) => {
try {
const response = await loginFeedback(userInfo);
return response.data;
} catch (err) {
return rejectWithValue(err);
}
}
);
const initialState = {
isAuthenticated: false,
isLoading: false,
user: null,
error: null,
};
const userSlice = createSlice({
name: "users",
initialState,
reducers: {},
extraReducers: {
[login.pending]: (state, action) => {
state.isLoading = true;
state.isAuthenticated = false;
},
[login.fulfilled]: (state, action) => {
state.isLoading = false;
state.isAuthenticated = true;
state.user = action.payload;
},
[login.rejected]: (state, action) => {
state.isLoading = false;
state.isAuthenticated = false;
state.user = [];
state.error = action.payload.message;
},
},
});
export default userSlice.reducer;
So in my LoginModal.js
file, when the Login button is clicked, it will fire up the form submit function handleSubmit()
:
const handleSubmit = (e) => {
e.preventDefault();
dispatch(login({ email, password }))
// something else....
}
So in UserSlice.js
, login
function will take care of the async call to fetch data since I used createAsyncThunk
. The createAsyncThunk
will create three actions: pending
, fulfilled
, and rejected
. and I defined the actions accordingly in the extraReducers
in my userSlice
.
// userSlice.js
[login.pending]: (state, action) => {
state.isLoading = true;
state.isAuthenticated = false;
},
[login.fulfilled]: (state, action) => {
state.isLoading = false;
state.isAuthenticated = true;
state.user = action.payload;
},
[login.rejected]: (state, action) => {
state.isLoading = false;
state.isAuthenticated = false;
state.user = [];
state.error = action.payload.message;
},
So if the loginFeedback
succeeded, the isAuthenticated
state should be set as true
, and if the call is rejected it will be set as false
and we will have an error message show up in the form.
In my LoginModal.js
, I want to close the modal if the user authentication is succeeded, and if fails, then shows the error message. To treat the action like normal promise contents, I found this in Redux Toolkits (here):
The thunks generated by createAsyncThunk will always return a resolved promise with either the fulfilled action object or rejected action object inside, as appropriate.
The calling logic may wish to treat these actions as if they were the original promise contents. Redux Toolkit exports an unwrapResult function that can be used to extract the payload of a fulfilled action or to throw either the error or, if available, payload created by rejectWithValue from a rejected action.
So I wrote my handleSubmit
function as:
const handleSubmit = (e) => {
e.preventDefault();
dispatch(login({ email, password }))
.then(unwrapResult)
.then(() => {
if (isAuthenticated && modal) {
setEmail("");
setPassword("");
toggle();
}
})
.catch((error) => {
setHasError(true);
});
};
We first unwrapResult
, then if the promise returns succeeded plus the state isAuthenticated
and the modal
are true then we toggle
(close) the modal, otherwise we log the error.
However, the modal does not close even if I see the user/login/fulfilled
action executes by the Redux DevTool, and the isAuthenticated
state is set as true
.
In my understanding, the isAuthenticated
should already set to be true
when the login
thunk finishes, so we have everything ready when we call the .then()
method. Is it because I get the isAutheticated
state by useSelector
, so it requires some time to update itself? So we cannot guarantee React Redux already updated it when the promise return? Is there a better way to close the modal when succeeded?
I appreciate your help! You can find the demo here. ('right@gmail.com' + whatever password => success, other combination => rejection)
ANSWER
Answered 2021-Jun-13 at 13:07I think the return value from the Promise
inside the then
callback does signify that the login operation is successful. But that doesn't mean you will get isAuthenticated
as true
because your handleSubmit
would have been closing over the previous value of isAuthenticated
which was false
.
You would require to have a custom useEffect
which triggers on isAuthenticated
and other values that your logic requires.
The following changes should satisfy what you need :-
const toggle = useCallback(() => {
setHasError(false);
setModal((modal) => !modal);
}, []);
useEffect(() => {
if (isAuthenticated && modal) {
setEmail("");
setPassword("");
toggle();
}
}, [isAuthenticated, modal, toggle]);
const handleSubmit = (e) => {
e.preventDefault();
dispatch(login({ email, password }))
.then(unwrapResult)
.catch(() => setHasError(true));
};
QUESTION
as said in the title I'm trying my best to align the items to right side of the navbar I tried also ml-auto on Nav and mr-auto on items and ml-auto on items. But the reactstrap should stay on the left side. Example As seen on the picture. So I would appreciate help from you guys, I'm kinda new react and web development in general.
import React, { useState } from "react";
import {
Collapse,
Navbar,
NavbarToggler,
NavbarBrand,
Nav,
NavItem,
NavLink,
UncontrolledDropdown,
DropdownToggle,
DropdownMenu,
DropdownItem,
NavbarText,
} from "reactstrap";
const Example = (props) => {
const [isOpen, setIsOpen] = useState(false);
const toggle = () => setIsOpen(!isOpen);
return (
reactstrap
Team
Events
Unsere Beratung
Bipapo
TomLongSchlong
Der coole Reset
Social Media
Kontakt
);
};
export default Example;
ANSWER
Answered 2021-Jun-11 at 10:00This just worked for me I hope it will work for you too!
className="position-absolute top-0 end-0"
Best regards Bias
QUESTION
i am trying checkboxes (component) in react and trying to get all the variables checked. I wrote the code as:
import React, { Component } from 'react'
import {
Card,
Container,
CardBody,
Form,
FormGroup,
Label,
Input,
Button,
} from "reactstrap";
export default class Chk extends React.Component {
states={
Colornames:{
ship:false,
cabin:false,
grade:false,
rate:false,
marketing:false,
image:false
}
}
chkClick = (e) => {
var {name, checked} = e.target;
var name = e.target.name;
var checked = e.target.checked;
console.log("xxxxx", e.Colornames)
this.setState((e) => {
var SelectedSport = e.Colornames;
return SelectedSport[name]=checked;
});
};
render() {
var displaySports = Object.keys(this.states.Colornames);
console.log("aaaaaa", displaySports)
return (
Ship
Cabin
Grade
Rate
Marketing
Image
)
}
}
This is giving error:
TypeError: Cannot read property 'Colornames' of null
i feel its all fine with the code. Finally i need all the checkboxes value (checked: true/false) so that i can do a search from the data as per the checkboxes checked BTW i am using a mac machine with chrome browser.
ANSWER
Answered 2021-Jun-09 at 20:04Just went through the problem statement again, and found out that the state initialisation wasn't correct. While using the React Class Components, the state should be initialised inside the constructor. I have tried to make the function chkClick
a little simpler and everything is working as per exepctation.
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
colornames: {
ship: false,
cabin: false,
grade: false,
rate: false,
marketing: false,
image: false
}
}
}
chkClick = (e) => {
var { name, checked } = e.target;
console.log(name, checked);
this.setState((prevState) => {
return {
colornames: {
...prevState.colornames,
[name]: checked
}
}
});
}
render() {
return (
Ship
Cabin
Grade
Rate
Marketing
Image
)
}
}
QUESTION
After installing bootstrap with npm install bootstrap
I added the style to /pages/_app.js
like so:
import 'bootstrap/dist/css/bootstrap.css';
export default function App({ Component, pageProps }) {
return
}
However anything from it that uses javascript does not work at all, e.g. the Collapse example from their docs.
function App() {
return (
Link with href
Button with data-bs-target
Some placeholder content for the collapse component. This panel is hidden by default but revealed when the user activates the relevant trigger.
);
}
export default App
If I add import 'bootstrap/dist/js/bootstrap.js'
to /pages/_app.js
then it starts "working" as expected, until a page reload in which it says ReferenceError: document is not defined
(screenshot), which leads me to believe it's not possible or that I shouldn't try to use boostrap + react or next.js.
I had thought them dropping jquery meant that it should work just "out of the box" with frameworks like react (as in not needing react-boostrap or reactstrap anymore)
Is there a way to properly use boostrap 5 and nextjs? Or should I just try something else entirely or go back to using reactstrap (which currently seems to only support boostrap 4)?
ANSWER
Answered 2021-Jun-05 at 02:37You only imported bootstrap.css, you must import bootstrap's js file if you want to use collapse. And bootstrap's js require jquery and popper. However, react or nextjs doesn't recommend you to use jquery.
You can use one of 2 below libs alternative:
For latest bootstrap 5, you can use BootstrapCDN:
In _document.js, add 2 lines:
QUESTION
I'm currently working on a reactjs project, and I've been stuck on a concept for some time. I have several forms, each managed by a component (Class) and I would like to submit these forms (all together) when I click on a button that is in another component. I use the Reactstrap library for the forms.
I went through this answer, and this one which are similar to mine but none of them fully helped me.
ANSWER
Answered 2021-Jun-04 at 18:22I had to look for several solutions (using parent references) but none satisfied me. To solve my problem, I had to resort to redux. Create a state at the level of redux and connect the parent and the childrens to the store. So as soon as the parent validates the submission (using a button) in the onClick function , the state (props if we use mapStateToProps) is modified and the components children and parent are re-rendered; and we can use the componentWillReceiveProps function to detect the changing of the props and submit the form.
QUESTION
I started using react-hook-form
to validate my inputs, but the require rule is always triggering even if I typer/enter something in the input field.
import React, { useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { Button, Form, Label, Input } from "reactstrap";
const setErrorStyle = (name) => {
return {
borderColor: name ? "red" : "",
boxShadow: name ? "0 0 1.5px 1px red" : ""
};
};
const App = () => {
const [comment, setComment] = useState("");
const {
handleSubmit,
control,
formState: { errors }
} = useForm();
const submitForm = (data) => {
console.log(data);
};
return (
Note/Comment
(
setComment(e.target.value)}
aria-invalid={!!errors.commentNote}
style={setErrorStyle(errors.commentNote)}
/>
)}
/>
{errors.commentNote && (
required
)}
Submit
);
};
export default App;
Here is the SandBox for testing: https://codesandbox.io/s/modern-wind-6v2gp
Thanks
ANSWER
Answered 2021-Jun-02 at 16:35The reason is because you are overriding the state handling of the form. What you actually do is you maintain your own state this way. If you want react-hook-form
to maintain the state you need to remove the onChange
handling in the Input
and the useState
from your code:
import React from "react";
import { Controller, useForm } from "react-hook-form";
import { Button, Form, Label, Input } from "reactstrap";
const setErrorStyle = (name) => {
return {
borderColor: name ? "red" : "",
boxShadow: name ? "0 0 1.5px 1px red" : ""
};
};
const App = () => {
const {
handleSubmit,
control,
formState: { errors }
} = useForm();
const submitForm = (data) => {
console.log(data);
};
return (
Note/Comment
(
)}
/>
{errors.commentNote && (
required
)}
Submit
);
};
export default App;
QUESTION
I have two components, User and AppSettings. I'm trying to access their stores in the App component. I have tried several different things from reading react redux help docs, but I cannot figure out how to get my mapDispatchToProps function to work in App. The closest I get is the code below which throws the error TypeError: this.props.requestUser is not a function
Does anyone know how I should structure my mapDispatchToProps to correctly import my actionCreators from two stores? Or do I have something else wrong and am hunting in the wrong spot? Any help is much appreciated, thanks.
Error Screenshot
33 | }
34 |
35 | private fetchUser() {
> 36 | this.props.requestUser();
| ^ 37 | }
38 |
39 | public render() {
AppSettings.ts
import { Action, Reducer } from 'redux';
import { AppThunkAction } from './';
// app settings state
export interface AppSettingsState {
isLoading: boolean;
appSettings: AppSettings;
}
export interface AppSettings {
SiteTitle: string;
PrimaryBackgroundColor: string;
PrimaryFontColor: string;
FooterLinkColor: string;
}
// ACTIONS - descriptions of state transitions
interface RequestAppSettingsAction {
type: 'REQUEST_APP_SETTINGS';
}
interface ReceiveAppSettingsAction {
type: 'RECEIVE_APP_SETTINGS';
appSettings: AppSettings;
}
/* Declare a 'discriminated union' type. */
type KnownAction = RequestAppSettingsAction | ReceiveAppSettingsAction;
// ACTION CREATORS - These are functions exposed to UI components that will trigger a state transition.
// They don't directly mutate state, but they can have external side-effects (such as loading data).
export const actionCreators = {
requestAppSettings: (): AppThunkAction => (dispatch, getState) => {
/* Only load data if it's something we don't already have (and are not already loading) */
console.log("AppSettings fired");
const appState = getState();
if (appState && appState.appSettings) {
fetch(`appsettings`)
.then(response => response.json() as Promise)
.then(data => {
dispatch({ type: 'RECEIVE_APP_SETTINGS', appSettings: data });
});
dispatch({ type: 'REQUEST_APP_SETTINGS'});
}
}
};
/*
REDUCER - For a given state and action, returns the new state.
To support time travel, this must not mutate the old state.
*/
const unloadedState: AppSettingsState = {
isLoading: false,
appSettings: {
SiteTitle: "",
PrimaryBackgroundColor: "",
PrimaryFontColor: "",
FooterLinkColor: ""
}
};
export const reducer: Reducer = (state: AppSettingsState | undefined, incomingAction: Action): AppSettingsState => {
if (state === undefined) {
return unloadedState;
}
const action = incomingAction as KnownAction;
switch (action.type) {
case 'REQUEST_APP_SETTINGS':
return {
appSettings: state.appSettings,
isLoading: true
};
case 'RECEIVE_APP_SETTINGS':
return {
appSettings: action.appSettings,
isLoading: false
};
break;
}
return state;
};
User.ts
import { Action, Reducer } from 'redux';
import { isNullOrUndefined } from 'util';
import { AppThunkAction } from './';
import * as Cookies from '../Utilities/cookies';
export interface UserState {
isLoading: boolean;
loginError: string;
loggedIn: boolean;
user: User;
}
export interface User {
username: string;
email: string;
firstName: string;
lastName: string;
token: string
}
interface RequestUserAction {
type: 'REQUEST_USER';
}
interface ReceiveUserAction {
type: 'RECEIVE_USER';
loginError: string;
user: User;
}
type KnownAction = RequestUserAction | ReceiveUserAction;
export const actionCreators = {
requestUser: (event?: React.FormEvent) : AppThunkAction => (dispatch, getState) => {
const appState = getState();
var url = "";
var skip = false;
var params = {};
/* Two ways to get user info - they submitted the login form
* or they are already logged in and have a user object cookie */
if (event != undefined) {
event.preventDefault();
const target = event.target as typeof event.target & {
username: { value: string };
password: { value: string };
};
const username = target.username.value;
const password = target.password.value;
url = "user/login";
params = {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ username: username, password: password })
}
} else {
var cUser: string | null = Cookies.getCookie("user");
if (cUser) {
var user: User = JSON.parse(cUser);
url = "user";
params = {
method: "GET",
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + user.token
}
}
} else {
skip = true; // home page and never has or tried to login
}
}
if (appState && appState.user && !skip) {
fetch(url, params)
.then(response => {
if (!response.ok) {
throw new Error(response.status.toString());
} else {
return response.json() as Promise;
}
})
.then(data => {
dispatch({ type: 'RECEIVE_USER', user: data, loginError: "" });
})
.catch(error => {
dispatch({ type: 'RECEIVE_USER', user: {} as User, loginError: error.message });
});
dispatch({ type: 'REQUEST_USER' });
}
}
};
const unloadedState: UserState = {
isLoading: false,
loginError: "",
loggedIn: false,
user: {
username: "",
email: "",
firstName: "",
lastName: "",
token: ""
}
};
export const reducer: Reducer = (state: UserState | undefined, incomingAction: Action): UserState => {
if (state === undefined) {
return unloadedState;
}
const action = incomingAction as KnownAction;
switch (action.type) {
case 'REQUEST_USER':
return {
user: state.user,
loginError: "",
loggedIn: false,
isLoading: true,
};
case 'RECEIVE_USER':
var loggedIn = false;
if (!action.loginError) {
loggedIn = true;
Cookies.setCookie("user", JSON.stringify(action.user), 7);
} else {
loggedIn = false;
Cookies.eraseCookie("user");
}
return {
user: action.user,
loginError: action.loginError,
loggedIn: loggedIn,
isLoading: false
};
break;
}
return state;
};
App.tsx
import * as React from 'react';
import { Route } from 'react-router';
import Layout from './components/Layout';
import Home from './components/Home';
import Counter from './components/Counter';
import FetchData from './components/FetchData';
import CapacityGrid from './components/CapacityGrid';
import { connect } from 'react-redux';
import { Container } from 'reactstrap';
import { ApplicationState } from './store';
import * as AppSettingsStore from './store/AppSettings';
import * as UserStore from './store/User';
import './css/custom.css'
import { userInfo } from 'os';
type AppSettingsProps =
AppSettingsStore.AppSettingsState
& typeof AppSettingsStore.actionCreators
type UserProps =
UserStore.UserState
& typeof UserStore.actionCreators
class App extends React.PureComponent {
public componentDidMount() {
this.fetchAppSettings();
this.fetchUser();
}
private fetchAppSettings() {
this.props.requestAppSettings();
}
private fetchUser() {
this.props.requestUser();
}
public render() {
return (
{!this.props.isLoading &&
}
)
}
}
/* works
export default connect(
(state: ApplicationState) => state.user,
UserStore.actionCreators
)(App as any); */
/*const mapDispatchToProps = (dispatch: any) => ({
userActions: () => dispatch(UserStore.actionCreators.requestUser),
appActions: () => dispatch(AppSettingsStore.actionCreators.requestAppSettings),
});*/
const mapStateToProps = (state: ApplicationState) => ({
user: state.user,
appSettings: state.appSettings
});
const mapDispatchToProps = (
UserStore.actionCreators,
AppSettingsStore.actionCreators
);
export default connect(mapStateToProps, mapDispatchToProps)(App as any);
ANSWER
Answered 2021-May-29 at 19:13I was able to figure it out. I needed to use the spread operator to get both actionCreators in my matchDispatchToProps
I changed this
const mapStateToProps = (state: ApplicationState) => ({
user: state.user,
appSettings: state.appSettings
});
const mapDispatchToProps = (
UserStore.actionCreators,
AppSettingsStore.actionCreators
);
to this
const mapStateToProps = (state: ApplicationState) => ({
...state.user,
...state.appSettings
});
const mapDispatchToProps = ({
...UserStore.actionCreators,
...AppSettingsStore.actionCreators
});
QUESTION
I have a Input
with a useForm
register where the onChange is not working.
import React, { useState } from "react";
import { useForm } from "react-hook-form";
import { Form, FormGroup, Input } from "reactstrap";
const App = () => {
const [loginData, setLoginData] = useState({
email: null,
password: null
});
const {
register,
handleSubmit,
formState: { errors }
} = useForm();
const submitForm = (data) => {
console.log(data);
};
return (
console.log(e)}
{...register("email", { required: true })}
aria-invalid={errors.email ? "true" : "false"}
/>
{errors.email && (
required
)}
);
};
export default App;
When I change the value of email, the onChange is not being called. https://codesandbox.io/s/gracious-chatterjee-3e8i0
ANSWER
Answered 2021-May-28 at 18:07You need to use the component, as
register
isn't working with external controlled components like your component. Check this section in the docs for more information.
You can also omit useState
here and let RHF handle the state changes for you.
const App = () => {
const {
control,
handleSubmit,
formState: { errors }
} = useForm({
defaultValues: { email: "", password: "" }
});
const submitForm = (data) => {
console.log(data);
};
return (
(
onChange(value)}
className="has-input input-lg"
placeholder="Enter Email Address"
aria-invalid={!!errors.email}
/>
)}
/>
{errors.email && (
required
)}
);
};
QUESTION
Below is my Model (popup) code to send user email address to backend service. I have rendered this Model component in my Login Component. I am not able to submit this form. I don't know what i am missing here but my other forms are working fine. My Yup validations are working fine but when i click on "send" button , its not going inside onSubmit handler even if the field is validated.
import React from 'react';
import { Formik, Field, Form, ErrorMessage } from 'formik';
import * as Yup from 'yup';
import { errorMessage } from '../../utility/error-messages';
import { Button, Modal, ModalBody, ModalFooter } from 'reactstrap';
const TextFieldComponent = (props) => {
return (
{props.touched &&
props.touched[props.name] &&
props.errors &&
props.errors[props.name] !== undefined ? (
{msg}}
/>
) : (
{props.label}
)}
);
};
const setSchema = Yup.object({
email: Yup.string()
.email(errorMessage.emailValidation)
.required(errorMessage.emailRequired),
});
export const ForgetPasswordModal = ({ show = false, onClose = () => {} }) => {
debugger;
return (
<>
{
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
setSubmitting(false);
}, 400);
}}
>
{({ isSubmitting, errors, touched, handleChange, handleBlur }) => {
return (
<>
Reset password
Enter the email.
onClose(false)}
>
Cancel
Send
);
}}
);
};
ANSWER
Answered 2021-May-27 at 13:56It may be due to the Modal component. The modal is inside the form and if portal is used to render the modal it may be rendered outside the form. Can you try using form inside the modal and check if it works.
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install reactstrap
Support
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesExplore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits
Save this library and start creating your kit
Share this Page