1

I'm trying to alert the final value of the ace editor when a button is clicked. I know there's an onChange event for Ace Editor, just not sure on how to get that value into my handleClick function.

This is my current code:

import ReactAce from "react-ace";
import React from "react";

import "ace-builds/src-noconflict/mode-python";
import "ace-builds/src-noconflict/theme-twilight";

function onChange(newValue) {
  console.log("change", newValue);
}

function handleClick() {
  alert();
}

function CodeEditor(props) {
  return (
    <>
      <ReactAce
        value={props.value}
        mode="python"
        theme="twilight"
        showPrintMargin={false}
        setReadOnly={false}
        setValue={props.value}
        fontSize={18}
        style={{
          height: "620px",
          width: "100%",
        }}
        onChange={onChange}
      />
      <button onClick={handleClick}>Run Code</button>
    </>
  );
}
export default CodeEditor;

1 Answer 1

2

You can use a useState hook to manage the state of the text.

function CodeEditor(props) {
  // save the state here 
  const [ text, setText ] = useState('')
  const handleClick = () => {
    alert(text)
  }
  return (
    <>
      <ReactAce
        value={props.value}
        mode="python"
        theme="twilight"
        showPrintMargin={false}
        setReadOnly={false}
        setValue={props.value}
        fontSize={18}
        style={{
          height: "620px",
          width: "100%",
        }}
        // set the state when the value changes 
        onChange={(e) => setText(e.target.value)}
      />
      <button onClick={() => handleClick()}>Run Code</button>
    </>
Sign up to request clarification or add additional context in comments.

3 Comments

thanks, tried it out but seem to be getting a TypeError: Cannot read property 'value' of undefined. Looks to be happening on this line: onChange={(e) => setText(e.target.value)}
You need to pass in the value of instead of e.target.value.
replace with onChange={value => setText(value)}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.