I've implemented a video tag inside of a modal. On click of it the video should play. But, in my case, the same video is playing - node.js

I'm new to React and trying to create a video library. Everything is working fine but I'm not not able to render the video in a dynamic way. Even if what I have implemented is dynamic, but it's playing the same video.
server.js
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const app = express();
const port = process.env.PORT || 5000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
app.get('/latestVideos', (req, res) => {
res.send({
"videos": [
{
"thumbnail":"https://i.ytimg.com/vi/R-9i5NJsiL0/maxresdefault.jpg",
"source": "http://yt-dash-mse-test.commondatastorage.googleapis.com/media/car-20120827-85.mp4",
"title": "Lambhorghini",
"channelName":"Auto Car",
"views":"7 million views",
"lastUpdated":"3 weeks ago"
},
{
"thumbnail":"https://theawesomer.com/photos/2016/09/n6pdwdmjkze.jpg",
"source": "http://yt-dash-mse-test.commondatastorage.googleapis.com/media/motion-20120802-85.mp4",
"title": "Porche",
"channelName":"LoudWire",
"views":"1 million views",
"lastUpdated":"4 weeks ago"
},
{
"thumbnail":"https://i.ytimg.com/vi/bsSK1DccV_Y/maxresdefault.jpg",
"source": "http://yt-dash-mse-test.commondatastorage.googleapis.com/media/oops-20120802-85.mp4",
"title": "Havana",
"channelName":"Camila Cabello",
"views":"7 million views",
"lastUpdated":"6 weeks ago"
},
{
"thumbnail":"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS6njcfy1wTsPr8WAs5CubtCommlw2HAfYFIp1IY2yWRU2Oj1uM4A",
"source": "http://yt-dash-mse-test.commondatastorage.googleapis.com/media/car-20120827-85.mp4",
"title": "See You Again",
"channelName":"Charlie Puth",
"views":"3 million views",
"lastUpdated":"1 week ago"
},
{
"thumbnail":"https://i.ytimg.com/vi/Z0P9KW9B7nw/maxresdefault.jpg",
"source": "http://yt-dash-mse-test.commondatastorage.googleapis.com/media/motion-20120802-85.mp4",
"title": "Manali To Leh",
"channelName":"Mumbiker Nikhil",
"views":"5 million views",
"lastUpdated":"2 weeks ago"
},
{
"thumbnail":"https://mm.aiircdn.com/5/679578.jpg",
"source": "http://yt-dash-mse-test.commondatastorage.googleapis.com/media/oops-20120802-85.mp4",
"title": "Don't Talk To Strangers",
"channelName":"Ronnie James Dio",
"views":"1 million views",
"lastUpdated":"4 weeks ago"
}
]
});
});
app.listen(port, () => console.log(`Listening on port ${port}`));
latestVideos.js
import React, { Component } from 'react';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import {latestVideos} from "../../actions";
class LatestVideos extends Component {
componentWillMount() {
this.props.getLatestVideos();
}
render() {
const {latestVideos} = this.props;
return (
<div className="container">
<h4 className="mt-3 mb-3"><i className="fas fa-play mr-2"></i>Latest Videos</h4>
<div className="row">
{latestVideos && latestVideos.map((data, i) => {
return (
<div key={i} className="col-sm-4">
<div className="card mb-3">
<img className="card-img-top" data-toggle="modal" data-target="#myModal" src={data.thumbnail}></img>
<div className="modal fade" id="myModal">
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-body">
<video src={data.source} id="video"
poster="//shaka-player-demo.appspot.com/assets/poster.jpg"
controls muted autoPlay>
</video>
{console.log(data.s)}
</div>
</div>
</div>
</div>
<div className="card-body">
<h5 className="card-title">{data.title}</h5>
<p className="card-text">{data.channelName}</p>
<p>{data.views} | {data.lastUpdated}</p>
</div>
</div>
</div>
)
})}
</div>
</div>
)
}
}
const mapStateToProps = state => {
return {
latestVideos: state.videoBrowseList.latestVideos,
}
};
const mapActionsToProps = dispatch => {
return bindActionCreators({
getLatestVideos: latestVideos
}, dispatch);
};
export default connect(mapStateToProps, mapActionsToProps)(LatestVideos);
As you can from my code that is in server.js, everything is dynamic and in the frontend I have used map function. Everything is rendering, only the video, is playing the same video over and over again. Can someone please help me to troubleshoot this error

This is because your id myModal is same for all modal window, so only the first modal will be opened always, id should be unique.
Try the below code
<img className="card-img-top" data-toggle="modal" data-target={"#myModal" + i} src={data.thumbnail}></img>
<div className="modal fade" id={"myModal" + i}>
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-body">
<video src={data.source} id={"video" + i} poster="//shaka-player-demo.appspot.com/assets/poster.jpg"
controls muted autoPlay>
</video>
{console.log(data.s)}
</div>
</div>
</div>
</div>

Related

how to post form data to the server backend

Form.js
import "./form.css";
import React, {useEffect,useState} from "react";
import {addBeauty,deleteB} from "./beauty";
import Modal from "./Modal";
import axios from 'axios';
export default function CreateForm() {
const [Name, setName] = useState("");
const [Intro, setIntro] = useState("");
const [isOpen, setIsOpen] = useState();
const [backendData, setBackendData] = useState([{}]);
useEffect(()=>{
fetch("http://localhost:5000/api").then(
response=>response.json()
).then(
data=>{ setBackendData(data)}
)
},[]);
const handleSubmit = (event)=>{
event.preventDefault();
axios.post("http://localhost:5000/api",{
id: userList[userList.length - 1].id + 1, Name:Name, Introduction:Intro
}).then(res=>{
console.log(res.data);
})
}
return (
<div className="container">
<form className="add" onSubmit={handleSubmit} >
<h2>User</h2>
<label htmlFor= "name">Name</label>
<input type="text" value={Name}
onChange={(event) => {setName(event.target.value);}}/>
<label htmlFor= "Intro">Introduction</label>
<input type="text" value={Intro}
onChange={(event) => {setIntro(event.target.value);}}/>
<p></p>
<p></p>
<div className = "press">
<button id = "1" type="submit">
Add Beauty
</button>
<button id = "2"
onClick={clearForm}
>
Clear Form
</button>
</div>
</form>
<br></br>
<br></br>
<br></br>
<div className="display">
{(typeof userData.user1 === 'undefined')?(
<h1>Loading</h1>):(
backendData.user1.map((user,i)=>{
return (
<div>
<h1> {user.Name}</h1>
<button onClick={()=>{
setIsOpen(user.id);
}}>View in popup</button>
<Modal open={isOpen === user.id} onClose={()=>setIsOpen(undefined)}>
<h3> {User.Introduction}</h3>
</Modal>
</div>
);})
)}
</div>
</div>
);
}
Server.js
const express = require('express');
const app = express();
const cors=require("cors");
const corsOptions ={
origin:'*',
credentials:true, //access-control-allow-credentials:true
optionSuccessStatus:200,
}
app.use(cors(corsOptions)) // Use this after the variable declaration
app.get("/api",(req,res)=> {
res.json({"user1":[
{
id: 1,
Name: "Isabella",
},
{
id:2,
Name: "Catalina
}
]})
});
app.listen(5000,()=>{
console.log("Server started on port 5000");
})
I create a from using react. And I try to send the formdata to backend and insert the formdata into the data stored at backend using axios.post. But it doesn't work. I know it's because I didn't add the prefix of backend data "user1" in axios.post. But I am not sure how to do that. Could anyone help me with this?
You have not created the route on the server correctly. You have opened a route for GETting "/api" but you need to open a route for POSTing
Replace this line:
app.get("/api",(req,res)=> {
with
app.post("/api",(req,res)=> {
Hi Here you need to create one route for post API as below
app.post("/api",(req,res)=> {
console.log(req.body) //here you got the requested data.
res.send("Success !");
});

Can't perform a React state update on an unmounted component, I tried to fix it but it still renders the same problem

Hi there I am using Chart.js to create a doughnut chart, but I see to get "Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function." I will show my front end and back end that are relevant to the question. Also the server side fetches everything correctly and it also console logs it perfectly in the front end the way I need it to.
results. js basically the server side
router.get("/occ", authorization, async (req, res) => {
try {
console.log(req);
const result = await pool.query(
// "SELECT occupation,COUNT(occupation) FROM resources GROUP BY occupation;",
"SELECT occupation,COUNT(occupation) as values FROM resources GROUP BY occupation"
);
console.log(req);
console.log(result);
res.status(200).json({
status: "success",
data: {
occupationResults: result.rows, //this gets the one row we need
},
});
} catch (err) {
console.error(err.message);
}
});
DoughnutChart.js the component itself
import React, { Fragment, useState, useEffect } from "react";
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from "chart.js";
import { Doughnut } from "react-chartjs-2";
ChartJS.register(ArcElement, Tooltip, Legend);
const DoughnutChart = () => {
// const [user_id, setuserid] = useState("");
const [results, setResults] = useState([]);
async function getResults() {
try {
const response = await fetch(`http://localhost:4001/results/occ`, {
method: "GET",
//pass token with localstorage because it is stored in the header
headers: { token: localStorage.token },
});
const parseRes = await response.json();
// setpersonalForm(parseData);
console.log(parseRes);
// setUsername(parseRes.username);
setResults(parseRes.data.occupationResults);
// setuserid(parseRes.user_id); //
// const encryptStorage = new EncryptStorage('secret-key');
// removed the localstorage user id
console.log(parseRes.data.occupationResults);
} catch (err) {
console.error(err.message);
}
}
var data = {
labels: results?.map((x) => x.occupation),
datasets: [
{
label: `${results?.length} Amount per Occupation`,
data: results?.map((x) => x.values),
backgroundColor: [
"rgba(255, 99, 132, 0.2)",
"rgba(54, 162, 235, 0.2)",
"rgba(255, 206, 86, 0.2)",
"rgba(75, 192, 192, 0.2)",
"rgba(153, 102, 255, 0.2)",
"rgba(255, 159, 64, 0.2)",
],
borderColor: [
"rgba(255, 99, 132, 1)",
"rgba(54, 162, 235, 1)",
"rgba(255, 206, 86, 1)",
"rgba(75, 192, 192, 1)",
"rgba(153, 102, 255, 1)",
"rgba(255, 159, 64, 1)",
],
borderWidth: 1,
},
],
};
var options = {
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true,
},
},
legend: {
labels: {
fontSize: 26,
},
},
};
//going to make a request when we get to this component, this is for getting from database
useEffect(() => {
getResults();
return () => {
setResults({}); // I added this but it still doesn't work
};
}, []);
return (
<div>
<Doughnut data={data} options={options} height={400} />
</div>
);
};
export default DoughnutChart;
Where I am importing the component.
import React, { Fragment, useState, useEffect } from "react";
import DoughnutChart from "./DoughnutChart";
//import { toast } from "react-toastify";
import "./pagecss/home.css";
// import { FontAwesomeIcon } from "#fontawesome-free-solid";
// import { encryptStorage } from "./encrypt";
const Home = ({ setAuth }) => {
const [username, setUsername] = useState("");
const [user_id, setuserid] = useState("");
// const [personalForm, setpersonalForm] = useState([]);//
// const [Pform, setform] = useState(false);
async function getUsername() {
try {
const response = await fetch("http://localhost:4001/home/", {
method: "GET",
//pass token with localstorage because it is stored in the header
headers: { token: localStorage.token },
});
const parseRes = await response.json();
// setpersonalForm(parseData);
setUsername(parseRes.username);
setuserid(parseRes.user_id); //
// const encryptStorage = new EncryptStorage('secret-key');
// encryptStorage.setItem("user_id", parseRes.user_id);
console.log(parseRes);
} catch (err) {
console.error(err.message);
}
}
//going to make a request when we get to this component, this is for getting from database
useEffect(() => {
getUsername();
}, []);
return (
<Fragment>
<div className="container">
<div className="row">
<div className="col-md-4 col-sm-12 d-flex justify-content-center">
<div className="card-body text-center text-white">
<i className="fa-solid fa-bullseye fa-6x my-3 "></i>
<h2 className="card-title mb-4">Card Title</h2>
<p className="card-text">
Our Mission is to help the community out by helping people with
mental health issues
</p>
</div>
</div>
<div className="col-md-4 col-sm-12 d-flex justify-content-center">
<div className="card-body text-center text-white">
<i className="fa-solid fa-glasses fa-6x text-center my-3 "></i>
<h2 className="card-title mb-4">Card Title</h2>
<p className="card-text">
Our Mission is to help the community out by helping people with
mental health issues
</p>
</div>
</div>
<div className="col-md-4 col-sm-12 d-flex justify-content-center">
<div className="card-body text-center text-white pb-4">
<i className="fa-solid fa-hand-holding-medical fa-6x text-center my-3 "></i>
<h2 className="card-title mb-4">Card Title</h2>
<p className="card-text">
Our Mission is to help the community out by helping people with
mental health issues
</p>
</div>
</div>
</div>
</div>
<div className="container-fluid">
<div className="row justify-content-around">
<div
className="card col-lg-5 col-md-6 col-sm-12 d-flex justify-content-center mb-5 "
id="CardOne"
>
<img
src={require("./pictures/ProPic.jpg")}
className="card-img-top"
id="pictureOne"
alt="..."
/>
<div className="card-body text-center text-black">
<h2 className="card-title mb-4">Alexey Aulov</h2>
<p className="card-text">
Hi my name is Alexey Aulov I am a senior at College of Staten
Island studying Information System and Informatics. I had the
original idea of Essential Health after I witnessed that
sometimes the best way for people to get mental help is to have
Therapist that can relate to you as much as possible to help you
out. Helping people gives me the most gratitude in life.
</p>
</div>
</div>
<div
className="card col-lg-5 col-md-6 col-sm-12 d-flex justify-content-center mb-5 "
id="CardTwo"
>
<img
src={require("./pictures/ProPic.jpg")}
className="card-img-top"
alt="..."
id="pictureTwo"
/>
<div className="card-body text-center text-black">
<h2 className="card-title mb-4">Card Title</h2>
<p className="card-text">
Our Mission is to help the community out by helping people with
mental health issues
</p>
</div>
</div>
</div>
<DoughnutChart />
</div>
</Fragment>
);
};
export default Home;

How to pass data from React form to Node code?

I was building a weather app using OpenWeather API. The API was fetched in Node, then data was passed to React front end, code as follows:
Node index.js
const express = require('express');
const cors = require('cors');
const app = express();
const axios = require('axios');
const dotenv = require('dotenv');
dotenv.config();
const url = `http://api.openweathermap.org/data/2.5/weather?q=london,uk&APPID=${process.env.REACT_APP_WEATHER_API_KEY}`;
app.use(cors());
app.get('/', (req, res) => {
res.send('go to /weather to see weather')
});
app.get('/weather', (req, res) => {
axios.get(url)
.then(response => {res.json(response.data)})
.catch(error => {
console.log(error);
});
})
let port = process.env.PORT || 4000;
app.listen(port, () => {
console.log(`App running on port ${port} `);
});
The weather data can then be viewed in http://localhost:4000/weather. Then React is used to display the data. Assume there is a simple React component to accept weather input and update state:
React WeatherForm.js
import React from 'react';
class WeatherForm extends React.Component {
constructor(props) {
super(props);
this.state = {
country: '',
city: ''
}
}
updateLocation(e) {
this.setState({
country: e.target.value,
city: e.target.value
});
}
render() {
return (
<form>
<div className="field">
<label className="label">Country</label>
<div className="control">
<input
className="input"
type="text"
placeholder="Type country name here"
onChange={e => this.updateLocation(e)} />
</div>
</div>
<div className="field">
<label className="label">City</label>
<div className="control">
<input
className="input"
type="text"
placeholder="Type city name here"
onChange={e => this.updateLocation(e)} />
</div>
</div>
<div className="field">
<div className="control">
<input
type='submit'
value='Search' />
</div>
</div>
</form>
)
}
}
export default WeatherForm
Question: How can I pass the country and city user input from the React app form to the country and city in the url variable in this line in the Node code?
const url = `http://api.openweathermap.org/data/2.5/weather?q=city,country&APPID=${process.env.REACT_APP_WEATHER_API_KEY}`
UPDATE I have updated the WeatherForm component as follows:
import React from 'react';
import Axios from 'axios';
class WeatherForm extends React.Component {
constructor(props) {
super(props);
this.state = {
country: '',
city: ''
}
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
const url = 'http://localhost:4000/weather';
const location = {
country: this.state.country,
city: this.state.city
}
Axios.post(url, location).then((res) => {
// what should I do here?
}).catch((e) => {
console.log(e);
})
}
updateLocation(e) {
this.setState({
country: e.target.value,
city: e.target.value
});
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<p className="title">Weather</p>
<p className="subtitle">Check weather by city and country</p>
<div className="field">
<label className="label">Country</label>
<div className="control">
<input
className="input"
type="text"
placeholder="Type country name here"
onChange={e => this.updateLocation(e)} />
</div>
</div>
<div className="field">
<label className="label">City</label>
<div className="control">
<input
className="input"
type="text"
placeholder="Type city name here"
onChange={e => this.updateLocation(e)} />
</div>
</div>
<div className="field">
<div className="control">
<input
type='submit'
value='Search' />
</div>
</div>
</form>
)
}
}
export default WeatherForm
and I got error: POST http://localhost:4000/weather 404 (Not Found)
You want to use http requests to send the data to your backend. You can either use the native window.fetch API to send the data via a post request, or you can use a third-party library (I recommend axios).
The recommended way to send a post request on form submit in react is to store the field data in state (use the onChange prop on the input fields to update the state whenever the input value changes), and then use a handler function that gets fired when the submit button is clicked (use the onClick prop for your button element).
The handler function should get the current state (the form input field data) and pass it into the post request as the body.
When your express API receives the request, it can parse the data, and then fire off it's own API request to the openWeather API with that data as the url parameters.
UPDATE:
Updating due to updated question.
You don't have a post route defined in your express API. Therefore it won't accept post requests at the /weather route. What you need to do is write a handler that accepts post requests:
app.post('/weather', (req, res, next) => {
let { country, city } = req.body.data;
// here you send a post request to the weather API url
// to retrieve the results, then send them back
// to your react app to display them
}

I am getting a Warning: A component is changing an uncontrolled input of type text to be controlled

I building a simple todo app using the MERN stack with router and able to get it going except the edit part. I have 3 routes, the "Todos" page where i use axios to get the data from my express server route. The "Add" page for create new todo and the "Edit" page for editing and deleting. Here's my todos page where each todo has a button that takes the id as a url parameter unto the Edit page.
That little pencil/paper icon on each todo is a button link that get's the ID on click. Here's my Edit page with the data.
The warning:
Here's my Todos page i'm using a custom hook to fetch the data from express server route:
import React from 'react';
import useGetAPI from '../custom_hooks/useGetAPI';
import Todo from './todo_item/Todo';
const Todos = () =>{
const data = useGetAPI('http://localhost:4000');
return (
<div className="page">
<div className="page-header">
<h1>Todo Lists</h1>
</div>
<div className="page-content">
<ul className="todo-list">
{
data.map((todo)=><Todo todo={todo} key={todo._id}/>)
}
</ul>
</div>
</div>
);
}
export default Todos;
Here's my custom hooks for fetching data - used in Todos.
import {useState,useEffect} from 'react';
import axios from 'axios';
const useGetAPI = (url)=>{
const [data,setData] = useState([]);
useEffect(()=>{
const fetchData = async ()=>{
const response = await axios.get(url);
const data = [...response.data];
const error = response.error;
if(error)
console.log(error)
else{
console.log(data);
setData(data);
}
};
fetchData();
},[url])
return data;
}
export default useGetAPI;
Here's my Edit Page
import React,{useState, useEffect, useContext, useCallback} from 'react';
import useGetApiWithParams from '../custom_hooks/useGetApiWithParams';
import {FaTelegramPlane} from 'react-icons/fa';
import axios from 'axios';
import { matchPath } from 'react-router'
const EditTodo = (props) =>{
const todoID = props.match.params.id;
const [todo,setTodo] = useState(null);
const responseData = useGetApiWithParams('http://localhost:4000/edit',todoID);
console.log(`Todo id: ${todoID}`);
/* Set default data from database */
useEffect(()=>{
setTodo(responseData);
},[responseData,setTodo]);
const [description,setDescription] = useState('');
const [responsible,setResponsible] = useState('');
const [priority,setPriority] = useState('');
const [completed,setCompleted] = useState(false);
const handleDescription = useCallback((e)=>{
setDescription(e.target.value);
},[setDescription]);
const handleResponsible = useCallback((e)=>{
setResponsible(e.target.value);
},[setResponsible]);
const handlePriority = useCallback((e)=>{
setPriority(e.target.value);
},[setPriority]);
const handleCompleted = useCallback((e)=>{
setCompleted(!completed);
},[completed,setCompleted])
const handleSubmit = useCallback((e)=>{
e.preventDefault();
console.log('Form submitted');
console.log(`Description ${description}`);
console.log(`Description ${responsible}`);
console.log(`Description ${priority}`);
console.log(`Description ${completed}`);
const updatedTodo = {
description,
responsible,
priority,
completed: false
}
axios.put(`http://localhost/4000/edit/${props.match.params.id}`, updatedTodo)
.then(res=>console.log(res.data))
.catch(function (error) {
console.log(error);
});
},[description,responsible,priority,completed,props.match.params.id]);
return (
<div className="page">
<div className="page-header">
<h1>Edit Todo</h1>
</div>
<div className="page-content">
<form id="edit-todo-form" className="todo-form" onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="description">Description:</label>
<input id="description" type="text" className="form-control" onChange={handleDescription} value={responseData.description} />
</div>
<div className="form-group">
<label htmlFor="responsible">Responsible:</label>
<input id="responsible" type="text" className="form-control" onChange={handleResponsible} value={responseData.responsible} />
</div>
<div className="form-group">
<label htmlFor="priorities">Priorities:</label>
<div id="priorities" className="form-radios">
<label htmlFor="radio1" className="radio-label">
<input name="priorityOptions" type="radio" id="radio1" value={responseData.priority} checked={priority === 'Low'} onChange={handlePriority}/>
<span className="radiomark"></span>
<span className="radiotext">Low</span>
</label>
<label htmlFor="radio2" className="radio-label">
<input type="radio" id="radio2" value={responseData.priority} checked={priority === 'Medium'} onChange={handlePriority}/>
<span className="radiomark"></span>
<span className="radiotext">Medium</span>
</label>
<label htmlFor="radio3" className="radio-label">
<input type="radio" id="radio3" value={responseData.priority} checked={priority === 'High'} onChange={handlePriority}/>
<span className="radiomark"></span>
<span className="radiotext">High</span>
</label>
</div>
</div>
<div className="form-group">
<label htmlFor="todo_completed">Status:</label>
<div id="todo_completed">
<label htmlFor="checkcompleted" className="check-label">
<input type="checkbox" id="checkcompleted" value={responseData.completed} onChange={handleCompleted}/>
<span className="checkmark"></span>
<span className="checktext">Completed</span>
</label>
</div>
</div>
<div className="form-group">
<button type="submit" className="form-btn"><FaTelegramPlane />Save Changes</button>
</div>
</form>
</div>
</div>
);
}
export default EditTodo;
Here's my custom hook for fetching data based on the Todo ID i get from the url:
import { useState,useEffect } from 'react';
import axios from 'axios';
const useGetApiWithParams = (url,params)=>{
const [data,setData] = useState([]);
useEffect(()=>{
const fetchData = async ()=>{
const response = await axios.get(`${url}/${params}`);
const data = response.data;
const error = response.error;
if(error)
console.log(`Error: ${error}`)
else{
console.log(...data);
setData(...data);
}
};
fetchData();
},[url,params])
return data;
}
export default useGetApiWithParams;
And the url with id param from MongoDB:
How to solve this? I tried the placeholder and set it's value to the response data from api but it only works for text boxes, what about the radio buttons and checkboxes? They don't seem to set the default value. For example the radio button for setting the priority value={responseData.priority} doesn't set the value as you can see here:
What i would like to happen is: from the Todos page on clicking the edit button, the edit page with a form already filled with values based on the todo id from the url parameter and be able to edit the values as well. Need help, thanks!

React.js, onclick handler not changing state of the component

I am developing an app using node.js and react.js. I am trying to change the state of a component using an onclickhandler. The state of the component is not changing once it is rendered on the browser. However , if I try to do an alert in the onclickhandler its working.What might be the issue?
Here is the component that I'm trying to render :
var Server = module.exports = React.createClass({
getInitialState: function() {
return {
readOnly:"readOnly",
}
},
onButtonClick: function() {
this.setState({readOnly: ""});
},
render: function render() {
return (
<Layout {...this.props}>
<div id='index'>
<h1>Hello {this.props.name}!</h1>
<button onClick={this.onButtonClick}>Click Me</button>
<input readOnly={this.state.readOnly} />
<br/>
<a href='/'>Click to go to an react-router rendered view</a>
</div>
</Layout>
);
}
});
You need to set readOnly true or fasle.
onButtonClick: function() {
this.setState({readOnly: true or false});
}
It should work.
Here is a way you could add or remove an attribute to an element
var Example = React.createClass({
getInitialState: function () {
return {
readOnly: true,
}
},
onButtonClick: function () {
this.setState({readOnly: !this.state.readOnly});
},
render: function render() {
return (
<div {...this.props}>
<div id='index'>
<h1>Hello {this.props.name}!</h1>
<button onClick={this.onButtonClick}>Click Me</button>
<input {...(this.state.readOnly) ? {readOnly: 'readOnly'} : {}} />
<br/>
<a href='/'>Click to go to an react-router rendered view</a>
</div>
</div>
);
}
});
In this answer input value is editable only if u click the button otherwise the value of the input is not editable. This is one of the most simple way to achieve this...
import React from 'react';
import ReactDOM from 'react-dom';
class Sample extends React.Component{
constructor(props){
super(props);
this.state={
inputValue:"praveen"
}
this.valueChange = this.valueChange.bind(this);
}
valueChange(e){
this.setState({inputValue: e.target.value})
}
render(){
return(
<div>
<input type="text" value={this.state.inputValue } />
<button type="button" onClick={this.valueChange}>Edit</button>
</div>
)
}
}
export default Sample;
ReactDOM.render(
<Sample />,
document.getElementById('root')
);

Resources