Navigation menu not working in React - reactjs

Please help me to fix this navigation menu.Something here is not working.It has to change the clicked cell after click. I would be very grateful if you show me where is the problem
class MenuExample extends React.Component{
constructor(props) {
super(props);
this.state = {focused: 0};
}
clicked(index){
this.setState({focused: index});
};
render: {
return (
<div>
<ul>{ this.props.items.map(function(m, index){
var style = '';
if(this.state.focused == index){ style = 'focused'; }
return <li className={style} onClick={this.clicked.bind(this)}>{m}</li>;
}) }
</ul>
<p>Selected: {this.props.items[this.state.focused]}</p>
</div>
);
}
};
ReactDOM.render(
<MenuExample items={ ['Home', 'Services', 'About', 'Contact us'] } />,
document.getElementById('root')
);

Its a binding issue, you forgot to bind the map callback method, here:
this.props.items.map(function(m, index){.....})
Use arrow function to maintain the context, like this:
this.props.items.map((m, index) => {.....})
Check the working code:
class MenuExample extends React.Component{
constructor(){
super();
this.state = { focused: 0 };
}
clicked(index){
this.setState({focused: index});
}
render() {
return (
<div>
<ul>{ this.props.items.map((m, index) => {
var style = '';
if(this.state.focused == index){
style = 'focused';
}
return <li className={style} onClick={this.clicked.bind(this, index)}>{m}</li>
}) }
</ul>
<p>Selected: {this.props.items[this.state.focused]}</p>
</div>
);
}
}
ReactDOM.render(
<MenuExample items={ ['Home', 'Services', 'About', 'Contact us'] } />,
document.getElementById('container')
);
* {
padding:0;
margin:0;
}
html{
font:14px normal Arial, sans-serif;
color:#626771;
background-color:#fff;
}
body{
padding:60px;
text-align: center;
}
ul{
list-style:none;
display: inline-block;
}
ul li{
display: inline-block;
padding: 10px 20px;
cursor:pointer;
background-color:#eee;
color:#7B8585;
transition:0.3s;
}
ul li:hover{
background-color:#beecea;
}
ul li.focused{
color:#fff;
background-color:#41c7c2;
}
p{
padding-top:15px;
font-size:12px;
}
<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>
<div id='container'/>
Working Fiddle.

Related

How to create button like this UI?

I am trying to create this button in react.js but can not do this.
My problem is not a CSS is that how to hide and display this button like UI.
This is the button before click:
And this is button after click :
My question is about how to create this toggle button that click on it invisible and show pic 2?
this is my code:
import React, {Component} from "react";
import axios from "axios";
import ContentUploadForm from "../../../dashboardContent/ContentUploadForm";
class UploadContentButton extends Component {
constructor(props) {
super(props);
this.state = {
file : null
};
this.onFormSubmit = this.onFormSubmit.bind(this);
this.onChange = this.onChange.bind(this);
}
onFormSubmit (e) {
e.preventDefault();
const formData = new FormData();
formData.append('filename',this.state.file);
const config = {
headers : {
'content-type' : 'multipart/form-data'
}
};
axios.post("/api/momayezi/uploadFiles/upload" , formData , config)
.then((response) => {
alert("The file is successfully uploaded");
}).catch((error) => {
console.log(error)
})
}
onChange (e) {
this.setState({
file : e.target.files[0]
});
}
render() {
return (
<div className="mt-5">
<div className={"row"}>
<div className={"col-12"}>
<form onSubmit={this.onFormSubmit}>
<input accept={"jpg"} type={"file"} name={"filename"} onChange={this.onChange}/>
<button type={"submit"}>ارسال</button>
</form>
<ContentUploadForm />
</div>
</div>
</div>
);
}
}
export default UploadContentButton
You can have one state variable to toggle the screens.
const Component = () => {
const [showForm, setShowForm] = React.useState(false);
return (
<div>
{showForm ? (
<div>
<div onClick={() => setShowForm(false)}> ← go back </div>
<div className="second"> Form Here </div>
</div>
) : (
<div>
<button className="first" onClick={() => setShowForm(true)}> Click me </button>
</div>
)}
</div>
);
};
ReactDOM.render(<Component />, document.getElementById("app"))
.first {
width: 400px;
border-radius: 10px;
border: 1px solid grey;
}
.second {
width: 400px;
height: 200px;
margin-top: 20px;
border: 1px solid grey;
}
<script crossorigin src="https://unpkg.com/react#17/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#17/umd/react-dom.production.min.js"></script>
<div id="app"></div>

Show or Hide a particular element in react

I have to show list of faqs and I need to hide the answers of the questions. When I click on the question, the answer for that particular question need to be shown. My problem is, I have a bunch of questions and when i click the button, it will show all of the answer instead of the specific answer to that question.
class Faqs extends Component {
constructor(props){
super(props);
this.state = {
isHidden: true
}
}
toggleHidden () {
this.setState({
isHidden: !this.state.isHidden
})
}
render() {
return (
<div>
<span onClick={() => this.toggleHidden()}><strong>This is the question</strong></span>
{!this.state.isHidden && <p>Answer for the question</p>} <br/>
<span onClick={() => this.toggleHidden()}><strong>Question2</strong></span>
{!this.state.isHidden && <p>Answer2</p>} <br/>
<hr></hr>
</div >
)
}
}
You can break your component to one more level to have a sub component which renders only the question and corresponding answer. Pass the question and answers as props. In that way you can use the same component for all questions and yet every question/answer pair will have their own state.
class Faq extends Component{
state = {isHidden: true}
toggleHidden = ()=>this.setState((prevState)=>({isHidden: !prevState.isHidden}))
render(){
return(
<div>
<span onClick={this.toggleHidden}>
<strong>{props.question}</strong></span>
{!this.state.isHidden && <p>{props.answer}</p>}
</div>
)
}
}
class Faqs extends Component {
render() {
return (
<div>
<Faq question={"Question 1"} answer={"answer 1"} />
<Faq question={"Question 2"} answer={"answer 2"} />
</div >
)
}
}
Ideally you would list FAQs in some kind of list - then as you iterate over them, each will have an index number assigned to it - then as you toggle individual answers, you store that index in the state and operate on DOM via that number.
edit. In current day and age, it's only appropriate to show example using hooks:
const {useState} = React;
const FaqApp = () => {
const [ selectedQuestion, toggleQuestion ] = useState(-1);
function openQuestion(index) {
toggleQuestion(selectedQuestion === index ? -1 : index);
}
const faqs = getFaqs();
return (
<div>
<h2>FAQs:</h2>
{faqs.map(( { question, answer}, index) => (
<div key={`item-${index}`} className={`item ${selectedQuestion === index ? 'open' : ''}`}>
<p className='question' onClick={() => openQuestion(index)}>{question}</p>
<p className='answer'>{answer}</p>
</div>
))}
</div>
)
}
function getFaqs() {
const faqs = [
{
question: 'Question 1',
answer: 'answer 1'
},
{
question: 'Question 2',
answer: 'answer 2'
}
];
return faqs;
}
ReactDOM.render(
<FaqApp />,
document.getElementById("react")
);
body {
background: #fff;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
h2 {
margin-bottom: 11px;
}
.item + .item {
margin-top: 11px;
}
.question {
font-weight: bold;
cursor: pointer;
}
.answer {
display: none;
}
.open .answer {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>
older version of this post:
I've written a quick example that allows you to have multiple questions:
class FaqApp extends React.Component {
constructor(props) {
super(props)
this.state = {
// start the page with all questions closed
selectedQuestion: -1
};
this.openQuestion = this.openQuestion.bind(this);
}
getFaqs() {
// some service returning a list of FAQs
const faqs = [
{
question: 'Question 1',
answer: 'answer 1'
},
{
question: 'Question 2',
answer: 'answer 2'
}
];
return faqs;
}
openQuestion(index) {
// when a question is opened, compare what was clicked and if we got a match, change state to show the desired question.
this.setState({
selectedQuestion: (this.state.selectedQuestion === index ? -1 : index)
});
}
render() {
// get a list of FAQs
const faqs = this.getFaqs();
return (
<div>
<h2>FAQs:</h2>
{faqs.length && faqs.map((item, index) => (
<div key={`item-${index}`} className={`item ${this.state.selectedQuestion === index ? 'open' : ''}`}>
<p className='question' onClick={() => this.openQuestion(index)}>
{item.question}
</p>
<p className='answer'>
{item.answer}
</p>
</div>
))}
</div>
)
}
}
ReactDOM.render(<FaqApp />, document.querySelector("#app"))
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
h2 {
margin-bottom: 11px;
}
.item + .item {
margin-top: 11px;
}
.question {
font-weight: bold;
cursor: pointer;
}
.answer {
display: none;
}
.open .answer {
display: block;
}
<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>
<div id="app"></div>
The issue is that you're using one boolean piece of state to control the logic for multiple pieces. This is a classic scenario to use separate components.
Create a new component ToggleQuestion that encapsulates the mechanic of show/reveal.
The Faqs component instead manages a list of ToggleQuestion components.
const QUESTIONS = [
{ title: 'q1', answer: 'a1' },
{ title: 'q2', answer: 'a2' }
]
class ToggleQuestion extends React.Component {
constructor (props) {
super(props)
this.state = { isHidden: true }
}
toggleHidden () {
this.setState({ isHidden: !this.state.isHidden })
}
render () {
const { question, answer } = this.props
const { isHidden } = this.state
return (
<div>
<span>{question}</span>
{ !isHidden && <span>{answer}</span> }
<button onClick={this.toggleHidden.bind(this)}>
Reveal Answer
</button>
</div>
)
}
}
class Faqs extends React.Component {
render () {
return (
<div>
{ QUESTIONS.map(question => (
<ToggleQuestion
question={question.title}
answer={question.answer}
/>
))}
</div>
)
}
}
ReactDOM.render(<Faqs />, document.getElementById('container'))
<div id='container'></div>
<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>
I would write a different handler for the answer. In the future if you need more logic for the answer will be scalable. Notice renderAnswer
class Faqs extends Component {
constructor(props){
super(props);
this.state = {
isHidden: true
}
}
toggleHidden () {
this.setState({
isHidden: !this.state.isHidden
})
}
renderAnswer() {
if (this.state.isHidden) {
return;
}
return (
<p>Answer</p>
);
}
render() {
return (
<div>
<span onClick={() => this.toggleHidden()}><strong>This is the question</strong></span>
{ this.renderAnswer() } <br/>
<span onClick={() => this.toggleHidden()}><strong>Question2</strong></span>
{ this.renderAnswer() } <br/>
<hr></hr>
</div >
)
}
}
This is another way to do what you want. (This one will only make it possible to have one open at a time)
class Faqs extends Component {
constructor(props){
super(props);
this.state = {
hiddenId: null,
}
}
setHiddenId(id) {
this.setState({
hiddenId: id
})
}
render() {
return (
<div>
<span onClick={() => this.setHiddenId('one')}><strong>This is the question</strong></span>
{this.state.hiddenId === 'one' && <p>Answer for the question</p>} <br/>
<span onClick={() => this.setHiddenId('two')}><strong>Question2</strong></span>
{this.state.hiddenId === 'two' && <p>Answer2</p>} <br/>
<hr></hr>
</div >
)
}
}

Rotating background color in ReactJS

I have this code in my JS folder...
var bgColors = {
"Default": "#81b71a",
"Blue": "#00B1E1",
"Cyan": "#37BC9B",
"Green": "#8CC152",
"Red": "#E9573F",
"Yellow": "#F6BB42"
};
class App extends Component {
constructor() {
super();
this.state = {
name: 'React'
};
}
render() {
return (
<div>
<Helmet>
<style>{'body { background-color: red; }'}</style>
</Helmet>
</div>
);
}
}
render(<App />, document.getElementById('root'));
As you can see. the background is set to red. How do I make the background color rotate colors every second or so? I want the colors to rotate through the list of colors I established.
var bgColors = {
default: "#81b71a",
blue: "#00B1E1",
cyan: "#37BC9B",
green: "#8CC152",
red: "#E9573F",
yellow: "#F6BB42",
};
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
bgColor: bgColors.default,
};
this.interval = setInterval(() => {
let randomColor = bgColors[
Object.keys(bgColors)[
Math.floor(Math.random() *
Object.keys(bgColors).length)
]
];
this.setState(() => ({bgColor: randomColor}))
}, 1000);
}
componentWillUnmount() {
clearInterval(this.interval)
}
render() {
return (
<div
style={{
height: '200px',
backgroundColor: this.state.bgColor
}}
>
Background color changes every second
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
<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>
<div id="root"></div>

ReactJS ReactCSSTransitionGroup why does it work one component but not another?

Trying to figure out why this ReactCSSTransitionGroup animation works:
class SlideExample extends React.Component{
constructor(props) {
super(props);
this.state = { visible: false };
this.handleClick = this.handleClick.bind(this)
}
handleClick() {
this.setState({ visible: ! this.state.visible });
}
render() {
return <div>
<button onClick={this.handleClick}>{this.state.visible ? 'Slide up' : 'Slide down'}</button>
<ReactCSSTransitionGroup
transitionName="example"
transitionEnterTimeout={300}
transitionLeaveTimeout={300}>
{
this.state.visible
? <div className='panel'>
<ul className="project-list">
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
</div>
: null
}
</ReactCSSTransitionGroup>
</div>
}
}
const ProjectList = (props) => {
return(
<div className="ProjectList">
<SlideExample />
</div>
);
}
But not like this:
class App extends Component {
constructor() {
super();
this.state = {
_isProjectNavOpen: true,
}
}
_toggleProjectNav() {
this.setState(prevState => ({
_isProjectNavOpen: !prevState._isProjectNavOpen,
}));
}
render() {
return(
<div className="App">
<Router>
<div className="main-content">
<Route path="/projects" component={(props, state, params) =>
<ProjectList
_toggleProjectNav={this._toggleProjectNav}
_isProjectNavOpen={this.state._isProjectNavOpen}
{...props} />} />
</div>
</Router>
</div>
);
}
}
const ProjectList = (props) => {
return(
<div className="ProjectList">
<div className="center title" onClick={props._toggleProjectNav} id="Menu">Menu</div>
<ReactCSSTransitionGroup
transitionName="example"
transitionEnterTimeout={300}
transitionLeaveTimeout={300}>
{
props._isProjectNavOpen
? <div className='panel'>
<ul className="project-list">
<li>xx one</li>
<li>xx two</li>
<li>xx three</li>
</ul>
</div>
: null
}
</ReactCSSTransitionGroup>
</div>
);
}
The CSS:
.panel {
width: 200px;
height: 100px;
background: green;
margin-top: 10px;
}
.example-enter {
height: 0px;
}
.example-enter.example-enter-active {
height: 100px;
-webkit-transition: height .3s ease;
}
.example-leave.example-leave-active {
height: 0px;
-webkit-transition: height .3s ease;
}
_toggleProjectNav is a prop passed down from a parent component that toggles the _isProjectNavOpen state true/false; it works in that the panel does hide/show, but without the animation... does it have to do with the state being passed from the parent? Trying to understand how ReactCSSTransitionGroup works.
Thanks!
This code works for me. In this case this is not a ReactCSSTransitionGroup issue. The issue is most probably related to the CSS. Pay attention, some browsers require initial height value before the transition. So you need something like this:
.example-leave {
height: 100px;
}

Changing custom control style dynamically

Changing custom control style dynamically
I am trying to use react to put red border around each custom field that is empty. array this.state.Fields contains all the controls to be checked.
I want to check every required control and if its value not set, change its style property. Since properties cannot be changed, I tried to use state but the problem is I'd need to have a separate vriable for each control:
<Control ref="controlLabel" name="controlLabel" type="1" onComponentMounted={this.register} label="Control Label:" required="1" value={this.state.controlLabel} localChange={this.handleControlLabelChange} inputStyle={{border: this.state.errControlLabelStyle}} />
I was wondering if there is a more elegant way to do that? Here is my code:
this.state.Fields.forEach((field) => {
if(field.props.required === "1"){
var validField = (field.props.value != '' && field.props.value != undefined);
if(!validField){
//set the field style dynamically
}
}
validForm=validForm && validField;
});
You could add validation logic inside Control itself.
var Control = React.createClass({
isValid: function() {
if (!this.props.required) {
return true;
}
return this.props.value !== '' && this.props.value !== undefined;
},
render: function() {
let value = this.props.value;
return <div className={this.isValid() ? 'item valid' : 'item invalid'}>{value}</div>;
}
});
var App = React.createClass({
render: function() {
return (
<div className="container">
{[
{
required: true,
value: ''
},
{
required: true,
value: 'abc'
},
{
required: false,
value: ''
}
].map((v, i) => <Control key={i} required={v.required} value={v.value} />)}
</div>
);
}
});
ReactDOM.render(
<App />,
document.getElementById('container')
);
.valid {
border-color: green;
}
.invalid {
border-color: red;
}
.item {
width: 200px;
height: 50px;
border-width: 1px;
border-style: solid;
margin: 1px;
display: flex;
}
.container {
display: flex;
}
<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>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>

Resources