How can I simulate a click on a Component? - javascript

I use React refs in my code and the end goal is to simulate a click on selected refs (you will see how they are selected in my code).
I tried to use the method ".click()" on my element, but the console shows me Uncaught TypeError: pinterest.click is not a function
When I log the "pinterest" var in the loop, I get a "Component".
[![enter image description here][1]][1]
Here is my code :
import React, { Component } from 'react'
import InterestBox from './InterestBox'
import Axios from 'axios'
export class InterestList extends Component {
constructor(props) {
super(props);
this.state = {pinterests: []}
this.pinterestRefs = React.createRef()
this.pinterestRefs.current = [];
}
componentDidMount() {
Axios.get('http://localhost:8000/api/interests')
.then((success) => {
this.setState({pinterests: success.data.data.interests});
})
}
componentDidUpdate(prevProps) {
console.log(JSON.stringify(prevProps));
console.log(JSON.stringify(this.props))
if(this.props.alreadyChecked != prevProps.alreadyChecked) {
this.props.alreadyChecked.forEach((item) => {
this.pinterestRefs.current.forEach((pinterest) => {
if(item == pinterest.props.id) {
console.log(pinterest)
pinterest.click();
}
})
console.log(item)
})
}
console.log(this.pin)
}
render() {
return (
<React.Fragment>
{Object.keys(this.state.pinterests).map((interest, i) => {
var pinterest = this.state.pinterests[interest];
var callbackRef = node => this.pinterestRefs.current[i] = node;
return <InterestBox id={pinterest.id} onClick={this.props.onClick} icon={pinterest.picture_src} title={pinterest.name} ref={callbackRef} />
})}
</React.Fragment>
)
}
}
export default InterestList
How can I simulate a click ?
Thank you !
PARENT CODE :
import axios from 'axios';
import * as Cookies from 'js-cookie';
import React, { Component } from 'react';
import Button from '../../components/Button';
import Dashboard from '../Dashboard';
import ErrorContainer from '../../components/ErrorContainer';
import InterestList from '../../components/register/InterestList';
export class EditUser extends Component {
constructor(props) {
super(props);
this.state = {loading: true, interests: []}
this.addInterest = this.addInterest.bind(this);
this.logState = this.logState.bind(this);
}
addInterest(id, name) {
var mid = 'm' + id;
console.log(this.state.interests[mid] == undefined)
if(this.state.interests[mid] == undefined) {
console.log(this.state);
this.setState((state) => {
state.interests[mid] = name;
return {interests: state.interests}
})
} else {
console.log('deleted')
var newInterest = this.state.interests;
delete newInterest[mid]
this.setState({interests: newInterest})
}
console.log(this.state.interests)
}
componentDidMount() {
var token = Cookies.get('token');
axios.get('http://localhost:8000/api/details', {headers: {"Accept": 'application/json', "Authorization": `Bearer ${token}`}}).then(
(success) => {
this.setState({
loading: false,
firstname : success.data.data.user.firstname,
lastname: success.data.data.user.lastname,
email: success.data.data.user.email,
dob: success.data.data.user.dob,
address: success.data.data.user.address,
uinterests: success.data.data.interests
})
}, (error) => {
this.props.history.push('/deconnexion');
}
)
var places = require('places.js');
var placesAutocomplete = places({
appId: "plZJLSHIW8M5",
apiKey: "0eddd2fc93b5429f5012ee49bcf8807a",
container: document.querySelector('#address-input')
});
}
logState() {
console.log(this.state);
}
render() {
return (
<Dashboard loading={this.state.loading}>
<h1 className="title">Modifier mon profil</h1>
<form className="user-form offer-update-form" onSubmit={this.handleSubmit}>
<label>Prénom :</label>
<input type="text" name="firstname" value={this.state.firstname} onChange={this.handleChange}></input> <br />
<label>Nom de famille :</label>
<input type="text" name="lastname" value={this.state.lastname} onChange={this.handleChange}></input> <br />
<label>Email :</label>
<input type="email" name="email" value={this.state.email} onChange={this.handleChange} /><br />
<label>Adresse :</label>
<input type="address" id="address-input" name="address" value={this.state.address} onChange={this.handleChange} /><br />
<label>Date de naissance :</label>
<input type="date" name="dob" value={this.state.dob} onChange={this.handleChange} /><br />
<InterestList alreadyChecked={this.state.uinterests} onClick={this.addInterest} />
<ErrorContainer errors={this.state.errors} />
<Button type="primary">Soumettre les changements</Button>
</form>
<Button type="danger" onClick={this.logState} />
</Dashboard>
)
}
}
export default EditUser
```
CHILDREN CODE :
```
import React, { Component } from 'react'
export class InterestBox extends Component {
constructor(props) {
super(props);
this.images = require('../../img/interests/*.svg');
this.state = {activated: false};
this.interest_box_content = React.createRef();
this.interest_text = React.createRef();
this.handleClick = this.handleClick.bind(this);
this.updateDimensions = this.updateDimensions.bind(this);
}
handleClick() {
this.props.handleClick(this.props.id, this.props.title);
this.setState(prevState => ({
activated: !prevState.activated
}))
}
updateDimensions() {
console.log((window.getComputedStyle(this.refs.interest_box_content).width))
this.refs.interest_text = (window.getComputedStyle(this.refs.interest_box_content).width)
}
render() {
return (
<div className="column is-one-fifth-desktop is-half-touch">
<div className="interest-box">
<div className="interest-box-adjuster">
<div ref={"interest_box_content"} className={"interest-box-content " + (this.state.activated == true ? 'interest-box-activated' : '')} onClick={this.handleClick}>
<img className="interest-icon" src={this.images[this.props.icon]} style={{'height': '50%'}}></img>
<i className="activated-icon fas fa-check"></i>
<span ref={"interest_text"} className="interest-text">{this.props.title}</span>
</div>
</div>
</div>
</div>
)
}
}
export default InterestBox
```
[1]: https://i.stack.imgur.com/hHiPv.png

Related

React Js renderings is functionalities not working

I am new to react . I am hared coded the username and password into js pages . I am trying to redirect to user into admin pages on the text fields values. Here is mentioned that username and password Admin then i want to redirect the user into admin page else into home page but is not working . I also defined the router as well into app.js files.
Here is the app.js .
import React from 'react';
import { Router, Route, Switch, Redirect } from 'react-router-dom';
import { connect } from 'react-redux';
import { history } from '../_helpers';
import { alertActions } from '../_actions';
import { PrivateRoute } from '../_components';
import { HomePage } from '../HomePage';
import { LoginPage } from '../LoginPage';
import { RegisterPage } from '../RegisterPage';
import CreateEmployeeComponent from '../EmployeeComponets/CreateEmployeeComponent';
import ViewEmployeeComponent from '../EmployeeComponets/ViewEmployeeComponent';
import AdminComponent from '../EmployeeComponets/AdminComponent';
class App extends React.Component {
constructor(props) {
super(props);
history.listen((location, action) => {
// clear alert on location change
this.props.clearAlerts();
});
}
render() {
const { alert } = this.props;
return (
<div className="jumbotron">
<div className="container">
<div className="col-sm-8 col-sm-offset-2">
{alert.message &&
<div className={`alert ${alert.type}`}>{alert.message}</div>
}
<Router history={history}>
<Switch>
<PrivateRoute exact path="/" component={HomePage} />
<Route path = "/add-employee/:id" component = {CreateEmployeeComponent} />
<Route path = "/view-employee/:id" component = {ViewEmployeeComponent} />
<Route path="/login" component={LoginPage} />
<Route path="/register" component={RegisterPage} />
<Route path ="/admin" component={AdminComponent} />
<Redirect from="*" to="/" />
</Switch>
</Router>
</div>
</div>
</div>
);
}
}
function mapState(state) {
const { alert } = state;
return { alert };
}
const actionCreators = {
clearAlerts: alertActions.clear
};
const connectedApp = connect(mapState, actionCreators)(App);
export { connectedApp as App };
Here is the code for Login.js
import React from 'react';
import { Link, Redirect } from 'react-router-dom';
import { connect } from 'react-redux';
import { userActions } from '../_actions';
class LoginPage extends React.Component {
constructor(props) {
super(props);
// reset login status
this.props.logout();
this.state = {
username: '',
password: '',
submitted: false
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(e) {
const { name, value } = e.target;
this.setState({ [name]: value });
}
handleSubmit(e) {
e.preventDefault();
this.setState({ submitted: true });
const { username, password } = this.state;
if (username && password) {
this.props.login(username, password);
}
else if(username==="Admin" && password==="Admin"){
localStorage.setItem("token" , "shjsshhbhbh")
this.setState({
loggingIn:true
})
}
}
render() {
if(this.state.loggingIn){
return <Redirect to ="/admin" />
}
const { loggingIn } = this.props;
const { username, password, submitted } = this.state;
return (
<div className="col-md-6 col-md-offset-3">
<h2>Login</h2>
<form name="form" onSubmit={this.handleSubmit}>
<div className={'form-group' + (submitted && !username ? ' has-error' : '')}>
<label htmlFor="username">Username</label>
<input type="text" className="form-control" name="username" value={username} onChange={this.handleChange} />
{submitted && !username &&
<div className="help-block">Username is required</div>
}
</div>
<div className={'form-group' + (submitted && !password ? ' has-error' : '')}>
<label htmlFor="password">Password</label>
<input type="password" className="form-control" name="password" value={password} onChange={this.handleChange} />
{submitted && !password &&
<div className="help-block">Password is required</div>
}
</div>
<div className="form-group">
<button className="btn btn-primary">Login</button>
{loggingIn &&
}
<Link to="/register" className="btn btn-link">Register</Link>
</div>
</form>
</div>
);
}
}
function mapState(state) {
const { loggingIn } = state.authentication;
return { loggingIn };
}
const actionCreators = {
login: userActions.login,
logout: userActions.logout
};
const connectedLoginPage = connect(mapState, actionCreators)(LoginPage);
export { connectedLoginPage as LoginPage };
Here is the private route code
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
export const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={props => (
localStorage.getItem('user')
? <Component {...props} />
: <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
)} />
)
Here is the admin page .
import React, { Component } from 'react'
import { Redirect } from 'react-router-dom';
import EmployeeService from '../services/EmployeeService';
class AdminComponent extends Component {
constructor(props) {
super(props)
const token =localStorage.getItem("token")
let loggedIn = true
{
if(token == null){
loggedIn - false
}
this.state ={
loggedIn
}
}
this.state = {
// step 2
id: this.props.match.params.id,
firstName: '',
lastName: '',
emailId: ''
}
this.changeFirstNameHandler = this.changeFirstNameHandler.bind(this);
this.changeLastNameHandler = this.changeLastNameHandler.bind(this);
this.saveOrUpdateEmployee = this.saveOrUpdateEmployee.bind(this);
}
// step 3
componentDidMount(){
// step 4
if(this.state.id === '_add'){
return
}else{
EmployeeService.getEmployeeById(this.state.id).then( (res) =>{
let employee = res.data;
this.setState({firstName: employee.firstName,
lastName: employee.lastName,
emailId : employee.emailId
});
});
}
}
saveOrUpdateEmployee = (e) => {
e.preventDefault();
let employee = {emailId: this.state.emailId,firstName: this.state.firstName, lastName: this.state.lastName};
console.log('employee => ' + JSON.stringify(employee));
// step 5
if(this.state.id === '_add'){
EmployeeService.createEmployee(employee).then(res =>{
this.props.history.push('/employees');
});
}else{
EmployeeService.updateEmployee(employee, this.state.id).then( res => {
this.props.history.push('/employees');
});
}
}
changeFirstNameHandler= (event) => {
this.setState({firstName: event.target.value});
}
changeLastNameHandler= (event) => {
this.setState({lastName: event.target.value});
}
changeEmailHandler= (event) => {
this.setState({emailId: event.target.value});
}
cancel(){
this.props.history.push('/employees');
}
getTitle(){
if(this.state.id === '_add'){
return <h3 className="text-center">Add Employee</h3>
}else{
return <h3 className="text-center">Update Employee</h3>
}
}
render() {
if(this.state.loggedIn === false)
{
return <Redirect to ="/login" />
}
return (
<div>
<h1>Welcome to adimin </h1>
<br></br>
<div className = "container">
<div className = "row">
<div className = "card col-md-6 offset-md-3 offset-md-3">
{
this.getTitle()
}
<div className = "card-body">
<form>
<div className = "form-group">
<label> Email Id: </label>
<input placeholder="Email Address" name="emailId" className="form-control"
value={this.state.emailId} onChange={this.changeEmailHandler}/>
</div>
<div className = "form-group">
<label> First Name: </label>
<input placeholder="First Name" name="firstName" className="form-control"
value={this.state.firstName} onChange={this.changeFirstNameHandler}/>
</div>
<div className = "form-group">
<label> Last Name: </label>
<input placeholder="Last Name" name="lastName" className="form-control"
value={this.state.lastName} onChange={this.changeLastNameHandler}/>
</div>
<button className="btn btn-success" onClick={this.saveOrUpdateEmployee}>Save</button>
<button className="btn btn-danger" onClick={this.cancel.bind(this)} style={{marginLeft: "10px"}}>Cancel</button>
</form>
</div>
</div>
</div>
</div>
</div>
)
}
}
export default AdminComponent
in your handleSubmit function always first if is true and after that javascript didn't check another else if.
Also you need add another state isAdmin and use it like this:
const { username, password } = this.state;
if (username==="Admin" && password==="Admin") {
this.props.login(username, password);
localStorage.setItem("token" , "adminsaddad")
this.setState({
loggingIn:true,
isAdmin:true
})
} else if (username && password) {
this.props.login(username, password);
localStorage.setItem("token" , "shjsshhbhbh")
this.setState({
loggingIn:true
})
}
Then check if the user is admin or not:
if(this.state.loggingIn){
if(this.state.isAdmin)
return <Redirect to ="/admin" />
else
return <Redirect to ="/" />
}
But this is not a safe way for the admin page, should also add the admin component in your PrivateRoute and check the token then redirect user.

Why the state is not updating in App.js after setting up this.setState?

Here is my simple to-do app program where I have made only one component which takes in the input form user and passes that input value to App.js to update items in App.js state.
todo-form.component.js
import React from 'react';
class SignInForm extends React.Component {
constructor(){
super();
this.state ={
temp: null
};
}
handleChange = (e) => {
e.preventDefault();
this.setState({
temp: e.target.value
},
console.log(this.state)
);
// this.props.addInput(e.target.value);
}
handleSubmit= (e) => {
e.preventDefault();
console.log(this.state.temp);
this.props.addInput(this.state.temp);
}
render(){
return(
<div className="container-form">
<form onSubmit={this.handleSubmit}>
<input
name="description"
type="text"
placeholder="add description"
onChange={this.handleChange}
value={this.state.input}
/>
<button type="submit">ADD</button>
</form>
</div>
);
}
}
export default SignInForm;
App.js
import React from 'react';
import './App.css';
import SignInForm from './components/todo-form/todo-form.component'
import ItemList from './components/todo-list/todo-list.component';
class App extends React.Component {
constructor(){
super();
this.state = {
input: []
};
}
addInput = (item) => {
let newInput=[...this.state.input,item];
console.log(newInput);
this.setState = ({
input: newInput
},
console.log(this.state)
);
}
render(){
return (
<div className="App">
<h1>TO-DO LIST</h1>
<SignInForm addInput={this.addInput} />
</div>
);
}
}
export default App;
On taking input the state inside todo-form.component.js is getting updated with the typed input value but on passing state.temp in handleChange function, the state inside App.js is not updating when addInput function is called.
Please help me on this issue and how my state is not getting updated in App.js??
Your setState is the problem. Have a look at my code.
App.js
class App extends React.Component {
state = {
input: [],
};
addInput = (item) => {
let newInput = [...this.state.input, item];
//setState should be this way
this.setState({
input: newInput,
});
};
render() {
return (
<div className="App">
<h1>TO-DO LIST</h1>
{this.state.input.map((el) => (
<li> {el}</li>
))}
<SignInForm addInput={this.addInput} />
</div>
);
}
}
export default App;
Login file.
class SignInForm extends React.Component {
// constructor(props) {
// super(props);
state = {
temp: null,
};
// }
handleChange = (e) => {
e.preventDefault();
this.setState({
temp: e.target.value,
});
// this.props.addInput(e.target.value);
};
handleSubmit = (e) => {
e.preventDefault();
console.log(this.state.temp);
this.props.addInput(this.state.temp);
};
render() {
return (
<div className="container-form">
<form onSubmit={this.handleSubmit}>
<input
name="description"
type="text"
placeholder="add description"
onChange={this.handleChange}
value={this.state.input}
/>
<button type="submit">ADD</button>
</form>
</div>
);
}
}
export default SignInForm;

using component state in another component react js

Im working on a little web app, and im stuck on getting the answers data from answer class that i created.
to sum the project, i have a class createQuiz, where i handle the input for question data, and i have an answerOptions state array to collect all the answers, but i created another component answer to have the states of the answers and when i modify them, the answeroptions dont update.
Here is the code for the answer class :
import React, {Component} from 'react';
import createQuiz from './CreateQuiz'
export default class Answer extends Component {
constructor(props) {
super(props);
this.handleInputChange = this.handleInputChange.bind(this);
this.onChangeAnswerValidity = this.onChangeAnswerValidity.bind(this);
this.ChangeValidityState = this.ChangeValidityState.bind(this);
this.state = {
answerText : '',
answerValidity : false
}
}
getCurrentState(){
return (this.state)
}
handleInputChange(event) {
this.setState({
answerText : event.target.value
})
}
onChangeAnswerValidity(event){
this.setState({
answerValidity : !event.target.value
})
}
ChangeValidityState(event){
this.setState({
answerValidity : !event.target.value
})
}
render() {
return (
<div>
<input type="text"
className="form-control"
value={this.state.answerText}
onChange={this.handleInputChange}
/>
<input type="radio"
className="form-control"
value={this.state.answerValidity}
checked={this.state.answerValidity}
onChange={this.onChangeAnswerValidity}
/>
</div>
)
}
}
and here is the code for the create quiz class :
import React, {Component} from 'react';
import axios from 'axios';
import Answer from './Answer';
export default class CreateQuiz extends Component {
constructor(props) {
super(props);
this.onChangeQuestion = this.onChangeQuestion.bind(this);
this.onChangeQuestionTitle = this.onChangeQuestionTitle.bind(this);
this.onChangeAnswerOptions = this.onChangeAnswerOptions.bind(this);
this.onAddItem = this.onAddItem.bind(this);
this.handleInputChange = this.handleInputChange.bind(this);
this.onChangeQuestionAutor = this.onChangeQuestionAutor.bind(this);
this.onChangeValue = this.onChangeValue.bind(this);
this.onChangeAnswerValidity = this.onChangeAnswerValidity.bind(this);
this.onSubmit = this.onSubmit.bind(this);
// this.GenerateAnswers = this.GenerateAnswers.bind(this);
this.state = {
questionTitle: '',
questionAutor: '',
question: '',
answers : [],
answerOptions: [],
}
}
onChangeValue = event => {
this.setState({ currentAnswerValue: event.target.value });
};
onAddItem = () => {
// not allowed AND not working
this.setState(state => {
const newAnswer = {
answerText : '',
answerValidity : false
};
const list = this.state.answerOptions.push(newAnswer);
return {
list,
};
});
};
handleInputChange(event) {
const newIds = this.state.answerOptions.slice() //copy the array
const index = this.state.answerOptions.findIndex((el) => (el.id === event.params.id))
newIds[index].answerText = event.target.value //execute the manipulations
this.setState({answerOptions: newIds}) //set the new state
}
onChangeAnswerValidity(event){
const newIds = this.state.answerOptions.slice() //copy the array
const index = this.state.answerOptions.findIndex((el) => el.answerText === event.target.value)
newIds[index].answerValidity = event.target.value //execute the manipulations
this.setState({answerOptions: newIds}) //set the new state
}
onChangeQuestionAutor(e){
this.setState({
questionAutor: e.target.value
});
}
onChangeQuestionTitle(e) {
this.setState({
questionTitle: e.target.value
});
}
onChangeQuestion(e) {
this.setState({
question: e.target.value
});
}
onChangeAnswerOptions(e) {
this.setState({
answerOptions: e.target.value
});
}
onSubmit(e) {
e.preventDefault();
console.log(`Form submitted:`);
console.log(`questionTitle: ${this.state.questionTitle}`);
console.log(`questionAutor: ${this.state.questionAutor}`);
console.log(`question: ${this.state.question}`);
// this.GenerateAnswers();
console.log(`answerOptions: ${this.state.answers}`);
const newQuiz = {
questionTitle: this.state.questionTitle,
questionAutor: this.state.questionAutor,
question: this.state.question,
answerOptions: this.state.answers,
}
axios.post('http://localhost:4000/quizzes/add', newQuiz)
.then(res => console.log(res.data));
this.setState({
questionTitle: '',
questionAutor: '',
question: '',
answers : [],
answerOptions: []
})
}
answerList(){
return this.state.answerOptions.map(function(currentAnswer, index) {
return <Answer answer = {currentAnswer} key = {index}/>;
});
}
// GenerateAnswers(){
// const newAnswers = this.state.answers
// this.state.answerOptions.map(function(currentAnswer, index){
// const newAnswer = this.state.answerOptions[index].getCurrentState()
// newAnswers.push(newAnswer)
// });
// this.setState({answers: newAnswers});
// }
render() {
return (
<div style={{marginTop: 20}}>
<h3>Create new question</h3>
<form onSubmit={this.onSubmit}>
<div className="form-group">
<label>Question Title: </label>
<input type="text"
className="form-control"
value={this.state.questionTitle}
onChange={this.onChangeQuestionTitle}
/>
</div>
<div className="form-group">
<label>Question Autor: </label>
<input type="text"
className="form-control"
value={this.state.questionAutor}
onChange={this.onChangeQuestionAutor}
/>
</div>
<div className="form-group">
<label>Question: </label>
<input type="text"
className="form-control"
value={this.state.question}
onChange={this.onChangeQuestion}
/>
</div>
<div>
<ul>
{this.answerList()}
</ul>
</div>
<div className="form-group">
<button type="button" onClick = {this.onAddItem} className="btn btn-primary"> Add answer </button>
</div>
<div className="form-group">
<input type="submit" value="submit Question" className="btn btn-primary" />
</div>
</form>
</div>
)
}
}
when i send the data to the database i always have in the answer fields empty string and false no update has been done.
thanks a lot,
Boubker ELAMRI
You’re modifying the list, so react doesn’t know it’s changed. You need to create a new array first, before setting the state
const list = Array.from(this.state.answerOptions)
list.push(newAnswer)

Can someone help me how to render immediately after the put and delete request

class App extends Component {
constructor() {
super();
this.state = {
currentProduct: null,
items: [],
};
this.handlepostSubmit= this.handlepostSubmit.bind(this);
}
componentDidMount() {
axios.get('http://localhost:3000/api/v1/products.json')
.then(res => {
const items = res.data;
this.setState({ items });
})}
handlepostSubmit = event => {
event.preventDefault();
const product = {
name: event.target[0].value,
style_no: event.target[1].value,
color: event.target[2].value,
material: event.target[3].value,
origin: event.target[4].value,
};
let token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
axios.defaults.headers.common['X-CSRF-Token'] = token;
axios.defaults.headers.common['Accept'] = 'application/json'
axios.put(`http://localhost:3000/api/v1/products/${this.state.currentProduct.id}`, {product})
.then(res => {
console.log(res);
console.log(res.data);
})
}
handleSubmit = event => {
event.preventDefault();
axios.delete
(`http://localhost:3000/api/v1/products/${this.state.currentProduct.id}`)
.then(res => {
})
}
render() {
const products = []
this.state.items.map(person =>
products.push(person))
return (
<div>
<div>
<Sidebar products={products} onSelect={product => this.setState({currentProduct: product})}/>
</div>
<div>
<Form product={this.state.currentProduct} />
</div>
<div>
<form onSubmit={this.handlepostSubmit}>
<label>Name:<input type="text" /></label>
<label>Style_no:<input type="text"/></label>
<label>Color:<input type="text" /></label>
<label>material<input type="text" /></label>
<label>Orgin<input type="text" /></label>
<input type="submit" value="Edit" />
</form>
</div>
<button onClick={this.handleSubmit}>Delete</button>
</div>
);}}
export default App
Right now, I am facing difficulties with how to render the component after the put and delete request. In the code above, after I click the edit and delete button, it does not render on the page immediately. I have to refresh the page to get the new information. Can someone give me information how to do this kind of stuff.
// APP COMPONENT
import React, { Component } from 'react';
import axios from 'axios';
import Sidebar from './sidebar';
import Form from './form';
class App extends Component {
constructor(props) {
super(props);
this.state = {
currentProduct: null,
products: [],
name: '',
styleNo: '',
color: '',
material: '',
origin: '',
};
this.handlepostSubmit = this.handlepostSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleProductSelected = this.handleProductSelected.bind(this);
this.handleDelete = this.handleDelete.bind(this);
}
// forceUpdateHandler(){
// this.forceUpdate();
// };
handleChange(e) {
const name = e.target.name;
this.setState({
[name]: e.target.value,
});
}
componentDidMount() {
axios.get('https://jsonplaceholder.typicode.com/posts').then(res => {
const items = res.data;
console.log(items);
this.setState({ products: items });
});
// http://localhost:3000/api/v1/products.json
}
handlepostSubmit(e) {
e.preventDefault();
const { name, styleNo, color, material, origin } = this.state;
console.log('selected name ', name);
const product = {
name,
style_no: styleNo,
color,
material,
origin,
};
console.log(product);
// let token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
// axios.defaults.headers.common['X-CSRF-Token'] = token;
// axios.defaults.headers.common['Accept'] = 'application/json'
// axios.put(`http://localhost:3000/api/v1/products/${this.state.currentProduct.id}`, {product})
// .then(res => {
// })
}
handleDelete(e) {
e.preventDefault();
console.log('on delete');
// axios.delete(`http://localhost:3000/api/v1/products/${this.state.currentProduct.id}`)
// .then(res => {
// })
}
// forceUpdate =event=>{
// location.reload(true);
// }
handleProductSelected(product) {
this.setState({
currentProduct: product,
});
}
render() {
const { products } = this.state;
return (
<div>
<div>
<Form product={this.state.currentProduct} />
</div>
<div>
<form onSubmit={this.handlepostSubmit}>
<label>
Name:
<input type="text" name="name" onChange={this.handleChange} />
</label>
<label>
Style_no:
<input type="text" name="styleNo" onChange={this.handleChange} />
</label>
<label>
Color:
<input type="text" name="color" onChange={this.handleChange} />
</label>
<label>
material
<input type="text" name="material" onChange={this.handleChange} />
</label>
<label>
Orgin
<input type="text" name="origin" onChange={this.handleChange} />
</label>
<input type="submit" value="Edit" onChange={this.handleChange} />
</form>
</div>
<div>
<button onClick={this.handleDelete}>Delete</button>
</div>
<div>
<Sidebar products={products} onSelect={this.handleProductSelected} />
</div>
</div>`enter code here`
);
}
}
export default App;
//Sidebar Component
import React from 'react';
class SideBar extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(product) {
const { onSelect } = this.props;
onSelect(product);
}
render() {
const { products } = this.props;
return products.map(product => {
// let boundItemClick = onItemClick.bind(this, x);
return (
<li key={product.id} onClick={() => this.handleClick(product)}>
<p> {product.id} </p>
{/* <p> {product.style_no}</p>
<p> {product.color}</p> */}
</li>
);
});
}
}
export default SideBar;
import React from 'react';
class Form extends React.Component {
render() {
const { product } = this.props;
return (
<section id="product">
<p>selected product: {product ? product.id : 'no product'} </p>
</section>
);
}
}
export default Form;

How to render data on submit in child component

I have a simple form on child component A. On submit I'm passing the data from the form to the parent component and storing the data in state.. I want to then move this data to a different child, child component B.(the sibling of A)
I'm having trouble getting the data to be rendered on submit in component B. I'm not sure how to trigger the rendering on submit or how to pass this information via props on submit.
Here is the Parent
class Msg extends React.Component {
constructor(props) {
super(props);
this.storeInput = this.storeInput.bind(this);
this.state = {
name: '',
msg: ''
};
}
storeInput (d) {
this.setState({
name: d.name,
msg: d.msg
})
}
render() {
return(
<div className='msgContainer'>
<Input
passBack={this.storeInput}/>
<Output />
</div>
)
}
}
Here is Component A
class Input extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.state = {
name: '',
msg: ''
};
}
handleChange(e) {
this.setState({[e.target.name]: e.target.value})
}
handleSubmit(e) {
e.preventDefault();
this.props.passBack(this.state);
}
render () {
const name = this.state.name;
const msg = this.state.msg;
return (
<div className='form-container'>
<form action="">
<label htmlFor="">name</label>
<input
name='name'
value={name}
onChange={this.handleChange}
type='text'></input>
<label htmlFor="">message</label>
<textarea
name='msg'
value={msg}
onChange={this.handleChange}
rows='5' cols='80'></textarea>
<input
onClick={this.handleSubmit}
type='submit'></input>
</form>
</div>
)
}
}
Here is Component B
class Output extends React.Component {
render () {
return(
<div className='output'>
</div>
)
}
}
Simply pass the state as props to Output like so:
Parent Component:
import React from 'react';
import Input from './Input';
import Output from './Output';
class Msg extends React.Component {
state = { name: '', msg: '' };
storeInput = d => {
this.setState({ name: d.name, msg: d.msg });
};
render() {
// destructure the state
const { name, msg } = this.state;
return (
<div className="msgContainer">
<Input passBack={this.storeInput} />
{/* pass the state as props to Output */}
<Output name={name} msg={msg} />
</div>
);
}
}
export default Msg;
Input.js
import React from 'react';
class Input extends React.Component {
state = { name: '', msg: '' };
handleChange = e => {
this.setState({ [e.target.name]: e.target.value });
};
handleSubmit = e => {
e.preventDefault();
this.props.passBack(this.state);
this.setState({ name: '', msg: '' }); // clear up the input after submit
};
render() {
const { name, msg } = this.state;
return (
<div className="form-container">
<form onSubmit={this.handleSubmit}>
<label htmlFor="">name</label>
<input
name="name"
value={name}
onChange={this.handleChange}
type="text"
/>
<label htmlFor="">message</label>
<textarea
name="msg"
value={msg}
onChange={this.handleChange}
rows="5"
cols="80"
/>
<input type="submit" />
</form>
</div>
);
}
}
export default Input;
Output.js
import React from 'react';
// destructure the props coming in from Msg
// no need for a class-based component
const Output = ({ name, msg }) => (
<div className="output">
<div>Output</div>
<p>{name}</p>
<p>{msg}</p>
</div>
);
export default Output;
Live demo: https://jsfiddle.net/c8th67zn/

Categories