React Login Page Button - reactjs

This is the full code of my login page. It is based on react-boilerplate .
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Helmet } from 'react-helmet';
import { FormattedMessage } from 'react-intl';
import { createStructuredSelector } from 'reselect';
import { compose } from 'redux';
import { LoginFooter } from 'containers/LoginFooter';
import injectSaga from 'utils/injectSaga';
import injectReducer from 'utils/injectReducer';
import makeSelectLoginPage, { makeSelectUsername, makeSelectPassword, makeSelectUserInfo, makeSelectSetErrMessage } from './selectors';
import reducer from './reducer';
import saga from './saga';
import messages from './messages';
import { InputText } from 'primereact/components/inputtext/InputText';
import { changePassword, changeUsername, submitForm, getErrMessage } from './actions';
import { Button } from 'primereact/components/button/Button';
import { Growl } from 'primereact/components/growl/Growl';
import { Panel } from 'primereact/components/panel/Panel';
export class LoginPage extends React.Component { // eslint-disable-line react/prefer-stateless-function
componentDidUpdate() {
this.props.changeMessage('');
}
render() {
if (this.props.setErrMessage) {
let msg = { severity: 'error', summary: 'Failure', detail: this.props.setErrMessage };
this.growl.show(msg);
}
return (
<div>
{/* <Helmet>
<meta name="description" content="Description of LoginPage" />
</Helmet> */}
<div className='ui-g ui-fluid login-img'>
<div className='ui-g-8 ui-sm-1 ui-md-3 ui-lg-7'>
</div>
<div className='ui-g-4 ui-sm-10 ui-md-6 ui-lg-4 loginpanelbar' style={{ marginLeft: '20px', marginTop: '28px', marginBottom: '13px' }}>
<Panel className='panellogin' style={{ paddingTop: '50px', paddingBottom: '50px' }}>
<div className='ui-g ui-fluid' >
<div className='ui-g-2 ui-sm-3 ui-md-2 ui-lg-2'>
</div>
<div className='ui-g-8 ui-sm-12 ui-md-8 ui-lg-8'>
<div className='logoimg' style={{ height: '80px' }}>
</div>
</div>
<div className='ui-g-2 ui-sm-3 ui-md-2 ui-lg-2'>
</div>
</div>
<div className='ui-g ui-fluid'>
<div className='ui-g-12 ui-sm-12 ui-md-12 ui-lg-12'>
<label for="name">Username</label>
<span class="md-inputfield" style={{ marginBottom: '20px', marginTop: '10px' }}>
<InputText id="netiinputfield1" style={{ height: '37px' }} type="text" value={this.props.username} onChange={(e) => { this.props.onChangeUsername(e.target.value) }} required class=" ui-state-default ui-corner-all ui-widget" />
</span>
</div>
</div>
<div className='ui-g ui-fluid'>
<div className='ui-g-12 ui-sm-12 ui-md-12 ui-lg-12'>
<label for="name">Password</label>
<span class="md-inputfield" style={{ marginBottom: '20px', marginTop: '10px' }}>
<InputText id="netiinputfield2" style={{ height: '37px' }} type="password" value={this.props.password} onChange={(e) => { this.props.onChangePassword(e.target.value) }} required class="ui-state-default ui-corner-all ui-widget" />
</span>
</div>
</div>
<div className='shortFont'>
<div className='ui-g ui-fluid'>
<div class='ui-g-12 ui-sm-6 ui-md-6 ui-lg-6'>
<div class="form-check" >
<input type="checkbox" className="form-check-input exampleCheck1" className='checkboxsize' />
<label class="form-check-label" for="exampleCheck1">Remember Me</label>
</div>
</div>
<div class='ui-g-12 ui-sm-6 ui-md-6 ui-lg-6' style={{ textAlign: 'right' }}>
<a href='#/'>Forget Password?</a>
</div>
</div>
</div>
<div className='ui-g ui-fluid' style={{ marginBottom: '13px' }}>
<div class="ui-g-12">
<Growl ref={(el) => this.growl = el} />
<Button label='LOGIN' onClick={this.props.submitLoginForm} />
</div>
</div>
</Panel>
</div>
<div className='ui-g-1 ui-sm-1 ui-md-1 ui-lg-1'>
</div>
</div>
<div className="login-img-footer">
<div class="textcss"><p>START WITH DIGITAL</p></div>
</div>
<div className="ui-g ui-fluid bottomPart"></div>
{/* <LoginFooter /> */}
</div>
);
}
}
LoginPage.propTypes = {
dispatch: PropTypes.func.isRequired,
username: PropTypes.any,
onChangeUsername: PropTypes.func,
password: PropTypes.any,
onChangePassword: PropTypes.func,
submitLoginForm: PropTypes.func,
userInfo: PropTypes.any,
changeMessage: PropTypes.any,
setErrMessage: PropTypes.any,
};
const mapStateToProps = createStructuredSelector({
loginpage: makeSelectLoginPage(),
username: makeSelectUsername(),
password: makeSelectPassword(),
userInfo: makeSelectUserInfo(),
setErrMessage: makeSelectSetErrMessage(),
});
function mapDispatchToProps(dispatch) {
return {
dispatch,
onChangeUsername: (value) => {
dispatch(changeUsername(value));
},
onChangePassword: (value) => {
dispatch(changePassword(value));
},
submitLoginForm: (evt) => {
dispatch(submitForm());
},
changeMessage: (evt) => {
dispatch(getErrMessage(evt));
}
};
}
const withConnect = connect(mapStateToProps, mapDispatchToProps);
const withReducer = injectReducer({ key: 'loginPage', reducer });
const withSaga = injectSaga({ key: 'loginPage', saga });
export default compose(
withReducer,
withSaga,
withConnect,
)(LoginPage);
The submit button works for mouse click, But i also need Enter key( key=13) to submit the form.
I tested some methods , but none of them worked out. How can i do it along with onClick and Enter Key.

You can simply wrap your form fields at tag and listen onSubmit event on it:
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Helmet } from 'react-helmet';
import { FormattedMessage } from 'react-intl';
import { createStructuredSelector } from 'reselect';
import { compose } from 'redux';
import { LoginFooter } from 'containers/LoginFooter';
import injectSaga from 'utils/injectSaga';
import injectReducer from 'utils/injectReducer';
import makeSelectLoginPage, { makeSelectUsername, makeSelectPassword, makeSelectUserInfo, makeSelectSetErrMessage } from './selectors';
import reducer from './reducer';
import saga from './saga';
import messages from './messages';
import { InputText } from 'primereact/components/inputtext/InputText';
import { changePassword, changeUsername, submitForm, getErrMessage } from './actions';
import { Button } from 'primereact/components/button/Button';
import { Growl } from 'primereact/components/growl/Growl';
import { Panel } from 'primereact/components/panel/Panel';
export class LoginPage extends React.Component { // eslint-disable-line react/prefer-stateless-function
componentDidUpdate() {
this.props.changeMessage('');
}
render() {
if (this.props.setErrMessage) {
let msg = { severity: 'error', summary: 'Failure', detail: this.props.setErrMessage };
this.growl.show(msg);
}
return (
<div>
{/* <Helmet>
<meta name="description" content="Description of LoginPage" />
</Helmet> */}
<div className='ui-g ui-fluid login-img'>
<div className='ui-g-8 ui-sm-1 ui-md-3 ui-lg-7'>
</div>
<div className='ui-g-4 ui-sm-10 ui-md-6 ui-lg-4 loginpanelbar' style={{ marginLeft: '20px', marginTop: '28px', marginBottom: '13px' }}>
<Panel className='panellogin' style={{ paddingTop: '50px', paddingBottom: '50px' }}>
<form onSubmit={this.props.submitLoginForm}>
<div className='ui-g ui-fluid' >
<div className='ui-g-2 ui-sm-3 ui-md-2 ui-lg-2'>
</div>
<div className='ui-g-8 ui-sm-12 ui-md-8 ui-lg-8'>
<div className='logoimg' style={{ height: '80px' }}>
</div>
</div>
<div className='ui-g-2 ui-sm-3 ui-md-2 ui-lg-2'>
</div>
</div>
<div className='ui-g ui-fluid'>
<div className='ui-g-12 ui-sm-12 ui-md-12 ui-lg-12'>
<label for="name">Username</label>
<span class="md-inputfield" style={{ marginBottom: '20px', marginTop: '10px' }}>
<InputText id="netiinputfield1" style={{ height: '37px' }} type="text" value={this.props.username} onChange={(e) => { this.props.onChangeUsername(e.target.value) }} required class=" ui-state-default ui-corner-all ui-widget" />
</span>
</div>
</div>
<div className='ui-g ui-fluid'>
<div className='ui-g-12 ui-sm-12 ui-md-12 ui-lg-12'>
<label for="name">Password</label>
<span class="md-inputfield" style={{ marginBottom: '20px', marginTop: '10px' }}>
<InputText id="netiinputfield2" style={{ height: '37px' }} type="password" value={this.props.password} onChange={(e) => { this.props.onChangePassword(e.target.value) }} required class="ui-state-default ui-corner-all ui-widget" />
</span>
</div>
</div>
<div className='shortFont'>
<div className='ui-g ui-fluid'>
<div class='ui-g-12 ui-sm-6 ui-md-6 ui-lg-6'>
<div class="form-check" >
<input type="checkbox" className="form-check-input exampleCheck1" className='checkboxsize' />
<label class="form-check-label" for="exampleCheck1">Remember Me</label>
</div>
</div>
<div class='ui-g-12 ui-sm-6 ui-md-6 ui-lg-6' style={{ textAlign: 'right' }}>
<a href='#/'>Forget Password?</a>
</div>
</div>
</div>
<div className='ui-g ui-fluid' style={{ marginBottom: '13px' }}>
<div class="ui-g-12">
<Growl ref={(el) => this.growl = el} />
<Button label='LOGIN' onClick={this.props.submitLoginForm} />
</div>
</div>
</form>
</Panel>
</div>
<div className='ui-g-1 ui-sm-1 ui-md-1 ui-lg-1'>
</div>
</div>
<div className="login-img-footer">
<div class="textcss"><p>START WITH DIGITAL</p></div>
</div>
<div className="ui-g ui-fluid bottomPart"></div>
{/* <LoginFooter /> */}
</div>
);
}
}
LoginPage.propTypes = {
dispatch: PropTypes.func.isRequired,
username: PropTypes.any,
onChangeUsername: PropTypes.func,
password: PropTypes.any,
onChangePassword: PropTypes.func,
submitLoginForm: PropTypes.func,
userInfo: PropTypes.any,
changeMessage: PropTypes.any,
setErrMessage: PropTypes.any,
};
const mapStateToProps = createStructuredSelector({
loginpage: makeSelectLoginPage(),
username: makeSelectUsername(),
password: makeSelectPassword(),
userInfo: makeSelectUserInfo(),
setErrMessage: makeSelectSetErrMessage(),
});
function mapDispatchToProps(dispatch) {
return {
dispatch,
onChangeUsername: (value) => {
dispatch(changeUsername(value));
},
onChangePassword: (value) => {
dispatch(changePassword(value));
},
submitLoginForm: (evt) => {
dispatch(submitForm());
},
changeMessage: (evt) => {
dispatch(getErrMessage(evt));
}
};
}
const withConnect = connect(mapStateToProps, mapDispatchToProps);
const withReducer = injectReducer({ key: 'loginPage', reducer });
const withSaga = injectSaga({ key: 'loginPage', saga });
export default compose(
withReducer,
withSaga,
withConnect,
)(LoginPage);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

Related

Uncaught TypeError: dispatcher.useSyncExternalStore is not a function

I am trying to change the state of bulma model using useSelector and useDispatch
like this
const isState = useSelector((state) => state.isActiveState)
Model.js is:
import React from 'react'
import "../CSS/Careers.css"
import { useSelector, useDispatch } from 'react-redux';
import { stateCheck } from '../Redux/ActiveState'
export default function Modal() {
const isState = useSelector((state) => state.isActiveState)
const dispatch = useDispatch()
return (
<div>
<div
style={{ padding: "0rem 0.5rem 0rem" }}
className={`modal ${isState}`} //this should change the state to 'is-active'
>
<div onClick={() => dispatch(stateCheck())} className="modal-background"></div>
<div style={{ borderRadius: "1.5rem" }} className="modal-card">
<header
style={{
borderBottom: "1px solid white",
backgroundColor: "#F2F5FF",
}}
className=""
>
<div style={{ padding: "17px 19px 20px" }} className="is-flex ">
<p
style={{ color: "#7209B7" }}
className="modal-card-title has-text-weight-semibold"
>
Apply For Job
</p>
<button
onClick={() => dispatch(stateCheck())}
className="delete"
aria-label="close"
></button>
</div>
</header>
<section
style={{ backgroundColor: "#F2F5FF" }}
className="modal-card-body"
>
<div style={{ padding: "0rem 3rem 0rem" }} className="field">
<div className="control has-icons-left ">
<input
className="input "
// style={{ width: "100%" }}
type="text"
placeholder="Name"
/>
<span className="icon is-small is-left">
<i className="fas fa-user"></i>
</span>
</div>
</div>
<div style={{ padding: "0rem 3rem 0rem" }} className="field">
<div className="control has-icons-left ">
<input className="input " type="email" placeholder="Email" />
<span className="icon is-small is-left">
<i className="fas fa-envelope"></i>
</span>
</div>
</div>
<div
style={{ padding: "0rem 3rem 0rem" }}
className="file is-medium"
>
<label style={{ border: "3px sold #7209B7" }} className="">
<input className="file-input" type="file" name="resume" />
<span
style={{ backgroundColor: "#F2F5FF" }}
className="file-cta"
>
<span className="file-icon">
<i
style={{ color: "#7209B7" }}
className="fas fa-upload"
></i>
</span>
<span style={{ color: "#7209B7" }} className="file-label">
Choose a file…
</span>
</span>
</label>
</div>
<p
style={{
padding: "0rem 3rem 0rem",
fontSize: "15px",
color: "#fcb01a",
}}
>
Select CV or Resume
</p>
</section>
<footer
style={{
borderTop: "1px solid white",
textAlign: "center",
height: "20%",
backgroundColor: "#F2F5FF",
}}
className=" has-text-centered"
>
<div
style={{ paddingTop: "9px", textAlign: "center" }}
className=""
>
<button style={{ backgroundColor: "#fcb01a" }} className="button">
Submit
</button>
</div>
</footer>
</div>
</div>
</div>
)
}
my redux file ActiveState.js is:
import { createSlice } from '#reduxjs/toolkit'
export const ActiveState = createSlice({
name: 'isActiveState',
initialState: {
value: 0,
},
reducers: {
stateCheck: (state) => {
// Redux Toolkit allows us to write "mutating" logic in reducers. It
// doesn't actually mutate the state because it uses the Immer library,
// which detects changes to a "draft state" and produces a brand new
// immutable state based off those changes
if (state.value == 0){
state.value = 'is-active';
// console.log(state.value)
}
else{
state.value = 0;
// console.log(state.value)
}
}
},
})
export const { stateCheck } = ActiveState.actions;
export default ActiveState.reducer;
and store.js is:
import { configureStore } from '#reduxjs/toolkit'
import ActiveState from './components/Redux/ActiveState'
export default configureStore({
reducer: {
stateChecker : ActiveState,
},
})
index.js is:
import React from 'react';
import ReactDOM from 'react-dom';
import './components/CSS/index.css';
import App from './App';
import store from './store'
import { Provider } from 'react-redux'
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
I have added model to the component where i want to use it and to trigger the model i have used:
onClick={() => dispatch(stateCheck())}
dispatch is working fine I have checked with console.log
the problem is when I try to get redux state with:
const isState = useSelector((state) => state.isActiveState)
i get the following error in console:
Uncaught TypeError: dispatcher.useSyncExternalStore is not a function
I am following redux official documentation:
https://react-redux.js.org/tutorials/quick-start
I have tried everything, checked imports, checked syntax and keywords, and checked every answer on StackOverflow but I'm still getting this error.
please help me I have been stuck here for almost a day.
This happens because react-redux is not supported yet with React 18 (React and React Native).
Downgrade react-redux to the previous version will solve your problem.
For me, with my React Native project, I downgraded:
"react-redux": "^8.0.1",
to
"react-redux": "^7.2.8",
Complete Code
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { Provider } from 'react-redux';
import store from './store/store';
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
Modal.js
// import '../CSS/Careers.css';
import React from 'react';
import { Button } from 'antd';
import { useSelector, useDispatch } from 'react-redux';
import { stateCheck } from './store/slice';
export default function Modal() {
const isState = useSelector((state) => state.stateChecker);
const dispatch = useDispatch();
console.log(isState);
return (
<div>
<Button onClick={() => dispatch(stateCheck(true))}>Open</Button>
<div
style={{
padding: '0rem 0.5rem 0rem',
// display: isState.value ? 'block' : 'none'
}}
className={`modal ${isState.value ? 'is-active' : ''}`} //this should change the state to 'is-active'
>
<div onClick={() => dispatch(stateCheck(false))} className='modal-background'></div>
<div style={{ borderRadius: '1.5rem' }} className='modal-card'>
<header
style={{
borderBottom: '1px solid white',
backgroundColor: '#F2F5FF'
}}
className=''
>
<div style={{ padding: '17px 19px 20px' }} className='is-flex '>
<p style={{ color: '#7209B7' }} className='modal-card-title has-text-weight-semibold'>
Apply For Job
</p>
<button onClick={() => dispatch(stateCheck(false))} className='delete' aria-label='close'></button>
</div>
</header>
<section style={{ backgroundColor: '#F2F5FF' }} className='modal-card-body'>
<div style={{ padding: '0rem 3rem 0rem' }} className='field'>
<div className='control has-icons-left '>
<input
className='input '
// style={{ width: "100%" }}
type='text'
placeholder='Name'
/>
<span className='icon is-small is-left'>
<i className='fas fa-user'></i>
</span>
</div>
</div>
<div style={{ padding: '0rem 3rem 0rem' }} className='field'>
<div className='control has-icons-left '>
<input className='input ' type='email' placeholder='Email' />
<span className='icon is-small is-left'>
<i className='fas fa-envelope'></i>
</span>
</div>
</div>
<div style={{ padding: '0rem 3rem 0rem' }} className='file is-medium'>
<label style={{ border: '3px sold #7209B7' }} className=''>
<input className='file-input' type='file' name='resume' />
<span style={{ backgroundColor: '#F2F5FF' }} className='file-cta'>
<span className='file-icon'>
<i style={{ color: '#7209B7' }} className='fas fa-upload'></i>
</span>
<span style={{ color: '#7209B7' }} className='file-label'>
Choose a file…
</span>
</span>
</label>
</div>
<p
style={{
padding: '0rem 3rem 0rem',
fontSize: '15px',
color: '#fcb01a'
}}
>
Select CV or Resume
</p>
</section>
<footer
style={{
borderTop: '1px solid white',
textAlign: 'center',
height: '20%',
backgroundColor: '#F2F5FF'
}}
className=' has-text-centered'
>
<div style={{ paddingTop: '9px', textAlign: 'center' }} className=''>
<button style={{ backgroundColor: '#fcb01a' }} className='button'>
Submit
</button>
</div>
</footer>
</div>
</div>
</div>
);
}
slice.js
import { createSlice } from '#reduxjs/toolkit';
export const ActiveState = createSlice({
name: 'isActiveState',
initialState: {
value: false
},
reducers: {
stateCheck: (state, action) => {
state.value = action.payload;
}
}
});
export const { stateCheck } = ActiveState.actions;
export default ActiveState.reducer;
store.js
import { configureStore } from '#reduxjs/toolkit';
import ActiveState from './slice';
export default configureStore({
reducer: {
stateChecker: ActiveState
}
});
It's not isActiveState. You should use the name of the reducer you specify in configureStore. stateChecker
const isState = useSelector((state) => state.stateChecker)
Now isState will have the value.
why do you use "ReactDOM.render" ?
you use a technology called useSyncExternalStore which comes with React18. Dont you need use ReactDOM.createRoot(element,options).render(component) ?
I had same issue because I had "react-dom": "^17.0.1" while react v18 installed. My set up was like this:
import ReactDOM from "react-dom";
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
</React.StrictMode>,
document.getElementById("root")
);
I switched the set up to:
import { createRoot } from "react-dom/client";
const container = document.getElementById("root");
const root = createRoot(container);
root.render(
<React.StrictMode>
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
</React.StrictMode>
);
it works. package versions
"react-redux": "^8.0.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
In my case I ended up removing the react-hot-loader and hot-loader/react-dom dependencies and its related Webpack config.
Since both of them only support till react-dom v17 which doesn’t have the new useSyncExternalStorage hook.
yarn add react#17.0.2
Downgrade react 18 to react 17

How can I call scrollIntoView on an ref in React

When I call someFun, I want to make formRef visible on the screen(it is on the top of the page, I may have scrolled to the bottom when I call someFun), is there standart way to do that?
function List(props) {
const formRef = useRef(null);
const someFun = params => {
if (formRef && formRef.current) {
//error FormRef.current.scrollIntoView is not a function
formRef.current.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'start' });
}
}
}
This is the form component used in the above parent component:
it is a ant design form component:
the link is here
https://3x.ant.design/components/form/#header
import { Form, Icon, Input, Button, Checkbox } from 'antd';
class NormalLoginForm extends React.Component {
handleSubmit = e => {
e.preventDefault();
this.props.form.validateFields((err, values) => {
if (!err) {
console.log('Received values of form: ', values);
}
});
};
render() {
const { getFieldDecorator } = this.props.form;
return (
<Form onSubmit={this.handleSubmit} className="login-form">
<Form.Item>
{getFieldDecorator('username', {
rules: [{ required: true, message: 'Please input your username!' }],
})(
<Input
prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
placeholder="Username"
/>,
)}
</Form.Item>
<Form.Item>
{getFieldDecorator('password', {
rules: [{ required: true, message: 'Please input your Password!' }],
})(
<Input
prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
type="password"
placeholder="Password"
/>,
)}
</Form.Item>
<Form.Item>
{getFieldDecorator('remember', {
valuePropName: 'checked',
initialValue: true,
})(<Checkbox>Remember me</Checkbox>)}
<a className="login-form-forgot" href="">
Forgot password
</a>
<Button type="primary" htmlType="submit" className="login-form-button">
Log in
</Button>
Or register now!
</Form.Item>
</Form>
);
}
}
const WrappedNormalLoginForm = Form.create({ name: 'normal_login' })(NormalLoginForm);
ReactDOM.render(<WrappedNormalLoginForm />, mountNode);
This how you can pass the ref from your NormalLoginForm to your List component.
In your List component you need to use forwardRef because it gives the child component a reference to a DOM element created by its parent component
Example
App
import "./styles.css";
import List from "./List";
import { useRef } from "react";
export default function App() {
const targetElement = useRef();
const scrollingTop = (event) => {
const elmnt = targetElement;
elmnt.current.scrollIntoView({
behavior: "smooth",
block: "center",
inline: "start"
});
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<p>lorem ipsum </p>
<div style={{ height: "200vh", backgroundColor: "orange" }}>
<h1>Example Form Tag </h1>
<button id="btnAppear" onClick={scrollingTop}>
Submit Scroll bottom
</button>
</div>
<List ref={targetElement} />
</div>
);
}
List
import { forwardRef } from "react";
const List = (ref) => {
return (
<div
style={{
backgroundColor: "purple",
paddingTop: "50px",
color: "white"
}}
ref={ref}
>
<h1>List View</h1>
</div>
);
};
export default forwardRef(List);
DEMO

using a value through react components

I'm new to React and been struggling with new challenges. Please write me your opinion and help me to get out of this challenge. I need to take the input value and append it in list area. Basically getting that state.inputValue and append it in ul of listArea.
This is InputTask component.
import React from 'react';
class InputTask extends React.Component {
state = { inputValue: ''}
onInputSubmit = (e) => {
this.setState({inputValue: e.target.value})
}
handleSubmit = (e) => {
e.preventDefault();
console.log('A name was submitted: ' + this.state.inputValue);
}
render() {
return (
<form className="ui input" onSubmit={this.handleSubmit} style={{marginRight:10}}>
<input type="text" value={ this.state.inputValue } onChange={this.onInputSubmit}/>
</form>
)
}
}
export default InputTask;
And this is listArea component.
import React from 'react';
class ListArea extends React.Component{
render() {
const style={
backgroundColor: "#f5d556",
height: "400px",
padding: "40px",
borderRadius: "20px"
};
const listStyle = {
backgroundColor: "green",
color: "white",
listStyle: "none",
textAlign: "left",
padding: "5px",
marginBottom: "10px",
borderRadius: "5px"
}
const iconStyle = {
float: "right"
}
const labelStyle = {
color: "white"
}
return(
<div className="ui form" style={{marginBottom:10}}>
<div className="field">
<div style={style}>
<ul style={{paddingLeft: 0}}>
<li style={listStyle}>
<div className="ui checkbox">
<input type="checkbox" name="example"/>
<label style={labelStyle}> hello there!</label>
</div>
<i className="white trash icon" style={iconStyle}></i>
</li>
</ul>
</div>
</div>
</div>
)
}
}
export default ListArea;
this is App component
import React from 'react';
import ReactDOM from 'react-dom';
import InputTask from "./components/inputTask";
import ListArea from "./components/listArea";
class App extends React.Component {
render() {
return (
<div className="ui container" style={{textAlign:'center'}}>
<h1>Tasks</h1>
<ListArea />
<InputTask />
</div>
);
}
}
ReactDOM.render(<App />,document.getElementById('root'));
In InputTask component at handleSubmit with this.props.InputSelected(this.state.inputValue);
I sent back selected input to it's parent(App.js)
import React from "react";
class InputTask extends React.Component {
state = { inputValue: "" };
onInputSubmit = (e) => {
this.setState({ inputValue: e.target.value });
};
handleSubmit = (e) => {
e.preventDefault();
console.log("A name was submitted: " + this.state.inputValue);
this.props.InputSelected(this.state.inputValue);
this.setState({ inputValue: "" });
};
render() {
return (
<form
className="ui input"
onSubmit={this.handleSubmit}
style={{ marginRight: 10 }}
>
<input
type="text"
value={this.state.inputValue}
onChange={this.onInputSubmit}
/>
</form>
);
}
}
export default InputTask;
In App component I got selected value with handleInputSelected and added it to list to send to ListArea component
import React from "react";
import InputTask from "./components/inputTask";
import ListArea from "./components/listArea";
class App extends React.Component {
state = { list: [] };
handleInputSelected = (input) => {
const { list } = { ...this.state };
list.push(input);
this.setState(list);
};
render() {
return (
<div className="ui container" style={{ textAlign: "center" }}>
<h1>Tasks</h1>
<ListArea list={this.state.list} />
<InputTask InputSelected={(input) => this.handleInputSelected(input)} />
</div>
);
}
}
export default App;
And finally in ListArea component with map on list I just append li element to ul.
import React from "react";
class ListArea extends React.Component {
render() {
console.log("data: ", this.props.data);
const style = {
backgroundColor: "#f5d556",
height: "400px",
padding: "40px",
borderRadius: "20px",
overflow: "scroll"
};
const listStyle = {
backgroundColor: "green",
color: "white",
listStyle: "none",
textAlign: "left",
padding: "5px",
marginBottom: "10px",
borderRadius: "5px"
};
const iconStyle = {
float: "right"
};
const labelStyle = {
color: "white"
};
console.log(this.props.data);
return (
<div className="ui form" style={{ marginBottom: 10 }}>
<div className="field">
<div style={style}>
<ul style={{ paddingLeft: 0 }}>
<li style={listStyle}>
<div className="ui checkbox">
<input type="checkbox" name="example" />
<label style={labelStyle}> hello there!</label>
</div>
<i className="white trash icon" style={iconStyle}></i>
</li>
{this.props.list.map((m) => (
<li style={listStyle}>
<div className="ui checkbox">
<input type="checkbox" name="example" />
<label style={labelStyle}> {m}</label>
</div>
<i className="white trash icon" style={iconStyle}></i>
</li>
))}
</ul>
</div>
</div>
</div>
);
}
}
export default ListArea;

Only 1 card is displaying on screen instead or 4 cards in row react and antd. Help I'm new at this

I'm using antd and little bit of bootstrap. please find the fault. I'm making this project from this video - https://www.youtube.com/watch?v=VihRQ_uhHtE&t=1915s . all the files for this movie page is shown below.
Here is the main page landingcomponent.js
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import {API_URL, API_KEY, IMAGE_URL} from '../../config/keys';
import {Typography, Row} from 'antd';
import MainImage from './MainImage';
import GridCard from './GridCard';
const {Title} = Typography;
function LandingPage() {
const [Movies, setMovies] = useState([])
useEffect( () => {
fetch(`${API_URL}movie/popular?api_key=${API_KEY}&language=en-US&page=1`)
.then(response => response.json())
.then(response => {
console.log(response);
setMovies(response.results);
})
}, [])
return(
<div style={{width:'100%'}}>
{Movies[0] &&
<MainImage image={`${IMAGE_URL}original${Movies[0].backdrop_path}`}
title={Movies[0].original_title}
text={Movies[0].overview} />}
<div className= "m-2">
<Title className='font-weight-bolder' style={{ color: 'black' }}>Latest Movies</Title>
<div>
<Row gutter={[16,16]}>
{Movies && Movies.map((movie, index) => (
<React.Fragment key={index}>
<GridCard
image={movie.poster_path && `${IMAGE_URL}original${movie.poster_path}`}
movieId={movie.id}
/>
</React.Fragment>
))}
</Row>
<div className="text-center">
<button className="btn btn-primary" onClick>Load More</button>
</div>
</div>
</div>
</div>
);
}
export default LandingPage;
and this is my gridcard.js file
import React from 'react';
import {Col} from 'antd'
function GridCard(props) {
return (
<Col lg={6} md={8} xs={24}>
<div className="position-relative">
<a href={`/movie/${props.movieId}`}>
<img style={{ width:'100%', height:'300px'}} alt="image" src={props.image} />
</a>
</div>
</Col>
)
}
export default GridCard;
also last MainImage.js file
import React from 'react';
import {Typography, Row} from 'antd';
const {Title} = Typography;
function MainImage(props) {
return(
<div className="img-responsive position-relative"
style={{
background: `url('${props.image}'), #1c1e1c`,
backgroundPosition: 'center',
backgroundSize: 'cover',
height: '50vh',
backgroundRepeat: 'no-repeat',
width: '100%',
}}
>
<div>
<div className='position-absolute' style={{ maxWidth:'450px', bottom: '2rem', marginLeft: '2rem' }} >
<Title className='h1' level={2}> {props.title} </Title>
<p style={{ color: 'white', fontSize: '1rem' }} > {props.text} </p>
</div>
</div>
</div>
);
}
export default MainImage;

Update the input value from one component in an other on runtime

I have a NotificationStepper Component which gets inputs from user, I need to update this input value in run time in another component named TabComponent. Both of the components are child components of SendNotification Component. How can i achieve that in reactjs.
EDIT
NotificationStepper.js
const styles = {
transparentBar: {
backgroundColor: 'transparent !important',
boxShadow: 'none',
paddingTop: '25px',
color: '#FFFFFF'
}
};
const useStyles = makeStyles((theme: Theme) =>
createStyles({
formControl: {
margin: theme.spacing(1),
minWidth: 120,
},
selectEmpty: {
marginTop: theme.spacing(2),
},
}),
);
function getSteps() {
return ['Create', 'Audience', 'Timing'];
}
function getStepContent(step, $this) {
switch (step) {
case 0:
return (
<div className="row">
<CardBox styleName="col-lg-12"
heading="">
<form className="row" noValidate autoComplete="off" style={{"flex-wrap":"no-wrap", "flex-direction": "column" }}>
<div className="col-md-12 col-12">
<TextField
id="campaign_name"
label="Campaign Name"
value={$this.state.name}
onChange={$this.handleChange('name')}
margin="normal"
fullWidth
/>
</div>
</form>
</CardBox>
</div>
);
default:
return 'Unknown step';
}
}
class NotificationStepper extends React.Component {
state = {
activeStep: 0,
name: '',
};
handleChange = name => event => {
this.setState({
[name]: event.target.value,
});
};
handleNext = () => {
this.setState({
activeStep: this.state.activeStep + 1,
});
};
handleBack = () => {
this.setState({
activeStep: this.state.activeStep - 1,
});
};
handleReset = () => {
this.setState({
activeStep: 0,
});
};
render() {
const steps = getSteps();
const {activeStep} = this.state;
return (
<div className="col-xl-12 col-lg-12 col-md-7 col-12">
<Stepper className="MuiPaper-root-custom" activeStep={activeStep} orientation="vertical">
{steps.map((label, index) => {
return (
<Step key={label}>
<StepLabel>{label}</StepLabel>
<StepContent className="pb-3">
<Typography>{getStepContent(index, this)}</Typography>
<div className="mt-2">
<div>
<Button
disabled={activeStep === 0}
onClick={this.handleBack}
className="jr-btn"
>
Back
</Button>
<Button
variant="contained"
color="primary"
onClick={this.handleNext}
className="jr-btn"
>
{activeStep === steps.length - 1 ? 'Finish' : 'Next'}
</Button>
</div>
</div>
</StepContent>
</Step>
);
})}
</Stepper>
{activeStep === steps.length && (
<Paper square elevation={0} className="p-2">
<Typography>All steps completed - you"re finished</Typography>
<Button onClick={this.handleReset} className="jr-btn">
Reset
</Button>
</Paper>
)}
</div>
);
}
}
export default NotificationStepper;
TabComponent.js
TabContainer.propTypes = {
children: PropTypes.node.isRequired,
dir: PropTypes.string.isRequired,
};
class TabComponent extends Component {
state = {
value: 0,
};
render() {
const {theme} = this.props;
return (
<div className="col-xl-12 col-lg-12 col-md-12 col-12" style={{"margin-top": "15px"}}>
<NotifCard key={0} data={{'name': 'Title of Notification', 'company': 'sayge.ai', 'image': require("assets/images/chrome.png"), 'description': 'Notification Message here'}} styleName="card shadow "/>
</div>
);
}
}
TabComponent.propTypes = {
theme: PropTypes.object.isRequired,
};
export default withStyles(null, {withTheme: true})(TabComponent);
and this is my SendNotification.js
const SendNotification = ({match}) => {
return (
<div className="dashboard animated slideInUpTiny animation-duration-3">
<ContainerHeader match={match} title={<IntlMessages id="sidebar.notification"/>}/>
<div className="row" style={{'flex-wrap': 'no wrap', "flex-direction": 'row'}}>
<div className="col-xl-7 col-lg-7 col-md-7 col-7">
<NotificationStepper/>
<div className='flex-class' style={{'width': '100%'}}>
<Button color="primary" style={{"align-self": "flex-end", "border" : "1px solid", "margin-left": "10px", "margin-bottom": "40px"}} size="small" className="col-md-2 col-2">Fetch</Button>
<Button color="primary" style={{"align-self": "flex-end", "border" : "1px solid", "margin-left": "10px", "margin-bottom": "40px"}} size="small" className="col-md-2 col-2" color="primary">Discard</Button>
</div>
</div>
<div className="col-xl-5 col-lg-5 col-md-5 col-5" style={{"padding-top": "20px"}}>
<span style={{"margin-left" : "20px", "font-weight": "bold"}}>Preview</span>
<TabComponent />
</div>
</div>
</div>
);
};
export default SendNotification;
i need to get the name value from NotificationStepper and Update it in pass it to in TabComponent.
There are plenty of tutorials about that. For instance, this.
import React, { Component, createRef } from "react";
class CustomTextInput extends Component {
textInput = createRef();
focusTextInput = () => this.textInput.current.focus();
render() {
return (
<>
<input type="text" ref={this.textInput} />
<button onClick={this.focusTextInput}>Focus the text input</button>
</>
);
}
}
import React, { useRef } from "react";
const CustomTextInput = () => {
const textInput = useRef();
focusTextInput = () => textInput.current.focus();
return (
<>
<input type="text" ref={textInput} />
<button onClick={focusTextInput}>Focus the text input</button>
</>
);
}

Resources